diff --git a/kiln-runtime/src/atomic_execution.rs b/kiln-runtime/src/atomic_execution.rs index 51dda748..f660a475 100644 --- a/kiln-runtime/src/atomic_execution.rs +++ b/kiln-runtime/src/atomic_execution.rs @@ -23,7 +23,6 @@ use core::sync::atomic::{ Ordering as AtomicOrdering, }; use core::time::Duration; -#[cfg(feature = "std")] use alloc::{ collections::BTreeMap, sync::Arc, @@ -35,8 +34,6 @@ use kiln_error::{ ErrorCategory, Result, }; -#[cfg(all(not(feature = "std"), not(feature = "std")))] -use kiln_foundation::bounded::BoundedVec; use kiln_foundation::{ traits::BoundedCapacity, MemArg, @@ -65,12 +62,7 @@ use crate::{ // Type alias for return results /// Result vector type for std environments -#[cfg(feature = "std")] pub type ResultVec = Vec; -/// Result vector type for `no_std` environments with bounded capacity -#[cfg(all(not(feature = "std"), not(feature = "std")))] -pub type ResultVec = - kiln_foundation::bounded::BoundedVec>; // Type alias for thread ID vectors - use bounded collections consistently type ThreadIdVec = kiln_foundation::bounded::BoundedVec< @@ -83,47 +75,17 @@ type ThreadIdVec = kiln_foundation::bounded::BoundedVec< macro_rules! result_vec { () => { { - #[cfg(feature = "std")] - { - Ok(Vec::new()) - } - #[cfg(all(not(feature = "std"), not(feature = "std")))] - { - let provider = kiln_foundation::safe_managed_alloc!(8192, kiln_foundation::budget_aware_provider::CrateId::Runtime)?; - kiln_foundation::bounded::BoundedVec::new(provider)? - } + Ok(Vec::new()) } }; ($item:expr; $count:expr) => { { - #[cfg(feature = "std")] - { - Ok(vec![$item; $count]) - } - #[cfg(all(not(feature = "std"), not(feature = "std")))] - { - let provider = kiln_foundation::safe_managed_alloc!(8192, kiln_foundation::budget_aware_provider::CrateId::Runtime)?; - let mut v = kiln_foundation::bounded::BoundedVec::new(provider)?; - for _ in 0..$count { - v.push($item)?; - } - Ok(v) - } + Ok(vec![$item; $count]) } }; ($($item:expr),+) => { { - #[cfg(feature = "std")] - { - Ok(vec![$($item),+]) - } - #[cfg(all(not(feature = "std"), not(feature = "std")))] - { - let provider = kiln_foundation::safe_managed_alloc!(8192, kiln_foundation::budget_aware_provider::CrateId::Runtime)?; - let mut v = kiln_foundation::bounded::BoundedVec::new(provider)?; - $(v.push($item)?;)+ - v - } + Ok(vec![$($item),+]) } }; } diff --git a/kiln-runtime/src/atomic_memory_model.rs b/kiln-runtime/src/atomic_memory_model.rs index 0a67d19a..14d33b59 100644 --- a/kiln-runtime/src/atomic_memory_model.rs +++ b/kiln-runtime/src/atomic_memory_model.rs @@ -61,18 +61,12 @@ type ResourceVec = kiln_foundation::bounded::BoundedVec; type OperationTypeVec = kiln_foundation::bounded::BoundedVec; -#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{ sync::Arc, vec::Vec, }; -#[cfg(feature = "std")] -use alloc::{ - sync::Arc, - vec::Vec, -}; -#[cfg(feature = "std")] use std::time::Instant; + /// WebAssembly atomic memory model implementation #[derive(Debug)] pub struct AtomicMemoryModel { @@ -120,7 +114,6 @@ impl AtomicMemoryModel { self.apply_pre_operation_ordering(&operation)?; // Record operation timing - #[cfg(feature = "std")] let start_time = Instant::now(); // Execute the atomic operation @@ -187,13 +180,10 @@ impl AtomicMemoryModel { }; // Record operation timing - #[cfg(feature = "std")] - { - let duration = start_time.elapsed(); - self.model_stats.total_execution_time += duration.as_nanos() as u64; - if duration.as_nanos() as u64 > self.model_stats.max_operation_time { - self.model_stats.max_operation_time = duration.as_nanos() as u64; - } + let duration = start_time.elapsed(); + self.model_stats.total_execution_time += duration.as_nanos() as u64; + if duration.as_nanos() as u64 > self.model_stats.max_operation_time { + self.model_stats.max_operation_time = duration.as_nanos() as u64; } // Apply memory ordering constraints after operation @@ -808,7 +798,6 @@ mod tests { assert!(result.data_races.is_empty()); } - #[cfg(feature = "std")] #[test] fn test_atomic_memory_model_creation() { let thread_manager = ThreadManager::new(ThreadConfig::default()).unwrap(); diff --git a/kiln-runtime/src/atomic_runtime.rs b/kiln-runtime/src/atomic_runtime.rs index 980ace25..9707dddd 100644 --- a/kiln-runtime/src/atomic_runtime.rs +++ b/kiln-runtime/src/atomic_runtime.rs @@ -44,7 +44,6 @@ use crate::atomic_execution::{ AtomicMemoryContext, }; -#[cfg(any(feature = "std", feature = "alloc"))] use crate::thread_manager::ThreadId; /// Provider trait for atomic operations across ASIL levels diff --git a/kiln-runtime/src/capability_integration.rs b/kiln-runtime/src/capability_integration.rs index 86d3a7dc..1ba4ee72 100644 --- a/kiln-runtime/src/capability_integration.rs +++ b/kiln-runtime/src/capability_integration.rs @@ -2,7 +2,6 @@ //! //! This module provides simple integration examples for the capability system. -#[cfg(feature = "std")] use kiln_foundation::capabilities::{ PlatformAllocator, PlatformCapabilityBuilder, @@ -12,7 +11,6 @@ use kiln_foundation::capabilities::{ use crate::prelude::*; /// Simple demonstration of capability integration -#[cfg(feature = "std")] pub fn create_simple_capability_provider( memory_limit: usize, ) -> Result { @@ -24,11 +22,9 @@ pub fn create_simple_capability_provider( } /// Simple allocator for demonstration -#[cfg(feature = "std")] #[derive(Debug)] struct SimpleAllocator; -#[cfg(feature = "std")] impl PlatformAllocator for SimpleAllocator { fn available_memory(&self) -> usize { 1024 * 1024 * 1024 // 1GB @@ -43,7 +39,6 @@ impl PlatformAllocator for SimpleAllocator { mod tests { use super::*; - #[cfg(feature = "std")] #[test] fn test_simple_capability_provider() { let provider = create_simple_capability_provider(1024 * 1024); diff --git a/kiln-runtime/src/cfi_engine.rs b/kiln-runtime/src/cfi_engine.rs index e5f61859..96bcd5a8 100644 --- a/kiln-runtime/src/cfi_engine.rs +++ b/kiln-runtime/src/cfi_engine.rs @@ -134,10 +134,7 @@ mod cfi_types { } // CFI imports temporarily disabled since CFI module is disabled -// #[cfg(not(feature = "std"))] -// use kiln_instructions::cfi_control_ops::{CfiHardwareInstruction, -// CfiSoftwareValidation}; Available for both std and no_std since CFI module is -// disabled +// Available for both std and no_std since CFI module is disabled use kiln_foundation::traits::DefaultMemoryProvider; use self::cfi_types::ShadowStackRequirement; @@ -148,11 +145,6 @@ pub use self::cfi_types::{ ShadowStackEntry, }; // CFI imports temporarily disabled since CFI module is disabled -// #[cfg(feature = "std")] -// use kiln_instructions::cfi_control_ops::{ -// CfiHardwareInstruction, ArmBtiMode, CfiSoftwareValidation, -// ShadowStackRequirement, ShadowStackEntry -// }; use crate::{ execution::ExecutionContext, prelude::{ diff --git a/kiln-runtime/src/clean_runtime_tests.rs b/kiln-runtime/src/clean_runtime_tests.rs index 03e1111d..d313dad0 100644 --- a/kiln-runtime/src/clean_runtime_tests.rs +++ b/kiln-runtime/src/clean_runtime_tests.rs @@ -4,7 +4,6 @@ //! instead of provider-embedded types, serving as a prototype for the //! full kiln-runtime migration. -#[cfg(any(feature = "std", feature = "alloc"))] use alloc::{ string::String, vec::Vec, @@ -16,7 +15,6 @@ use kiln_error::{ ErrorCategory, Result, }; -#[cfg(any(feature = "std", feature = "alloc"))] use kiln_foundation::{ CleanFuncType, CleanMemoryType, @@ -28,7 +26,6 @@ use kiln_foundation::{ }; /// Clean runtime module using provider-free types -#[cfg(any(feature = "std", feature = "alloc"))] pub struct CleanRuntime { /// Runtime type factory for allocation factory: RuntimeTypeFactory<65536>, @@ -40,7 +37,6 @@ pub struct CleanRuntime { tables: Vec, } -#[cfg(any(feature = "std", feature = "alloc"))] impl CleanRuntime { /// Create a new clean runtime pub fn new() -> Self { @@ -124,7 +120,6 @@ impl CleanRuntime { } } -#[cfg(any(feature = "std", feature = "alloc"))] impl Default for CleanRuntime { fn default() -> Self { Self::new() @@ -132,7 +127,6 @@ impl Default for CleanRuntime { } /// Clean function representation without provider embedding -#[cfg(any(feature = "std", feature = "alloc"))] #[derive(Debug, Clone)] pub struct CleanFunction { /// Function name @@ -143,8 +137,7 @@ pub struct CleanFunction { pub id: u32, } -/// Clean memory representation without provider embedding -#[cfg(any(feature = "std", feature = "alloc"))] +/// Clean memory representation without provider embedding #[derive(Debug, Clone)] pub struct CleanMemory { /// Memory name @@ -158,7 +151,6 @@ pub struct CleanMemory { pub data: Vec, } -#[cfg(any(feature = "std", feature = "alloc"))] impl CleanMemory { /// Read from memory pub fn read(&self, offset: u32, size: u32) -> Result> { @@ -188,7 +180,6 @@ impl CleanMemory { } /// Clean table representation without provider embedding -#[cfg(any(feature = "std", feature = "alloc"))] #[derive(Debug, Clone)] pub struct CleanTable { /// Table name @@ -201,14 +192,3 @@ pub struct CleanTable { pub elements: Vec>, // Function references } -// Provide empty implementations for no-alloc environments -#[cfg(not(any(feature = "std", feature = "alloc")))] -pub struct CleanRuntime; - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl CleanRuntime { - pub fn new() -> Self { - Self - } -} - diff --git a/kiln-runtime/src/component_impl.rs b/kiln-runtime/src/component_impl.rs index 7a32e564..83cbf392 100644 --- a/kiln-runtime/src/component_impl.rs +++ b/kiln-runtime/src/component_impl.rs @@ -4,86 +4,10 @@ // alloc is imported in lib.rs with proper feature gates -#[cfg(feature = "std")] use std::{collections::HashMap, sync::Arc}; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::{collections::BTreeMap, sync::Arc}; // Components traits imported below with full set -#[cfg(all(not(feature = "std"), not(feature = "std")))] -pub mod no_alloc { - use kiln_error::{Error, ErrorCategory, Result}; - use kiln_foundation::{ - bounded::{BoundedVec, MAX_COMPONENT_TYPES}, - safe_memory::{NoStdProvider, SafeSlice}, - verification::VerificationLevel, - }; - - /// A minimal component implementation for pure no_std environments - /// - /// This provides basic validation and introspection capabilities, - /// but does not support execution of components. - #[derive(Debug)] - pub struct MinimalComponent { - verification_level: VerificationLevel, - } - - impl MinimalComponent { - /// Creates a new minimal component - /// - /// # Arguments - /// - /// * `level` - The verification level to use - /// - /// # Returns - /// - /// * `Self` - A new minimal component - pub fn new(level: VerificationLevel) -> Self { - Self { verification_level: level } - } - - /// Gets the verification level for this component - /// - /// # Returns - /// - /// * `VerificationLevel` - The verification level - #[must_use] - pub const fn verification_level(&self) -> VerificationLevel { - self.verification_level - } - - /// Validates a component binary - /// - /// # Arguments - /// - /// * `binary` - The component binary data - /// - /// # Returns - /// - /// * `Result<()>` - Ok if the component is valid, Error otherwise - pub fn validate(binary: &[u8]) -> Result<()> { - #[cfg(feature = "decoder")] - { - // Use kiln-decoder's header validation - kiln_decoder::component::decode_no_alloc::verify_component_header(binary) - } - #[cfg(not(feature = "decoder"))] - { - // Basic validation - just check magic number - if binary.len() < 8 { - return Err(Error::parse_invalid_binary("Binary too small to be a valid component")); - } - // Check for WASM magic number (0x00 0x61 0x73 0x6D) - if &binary[0..4] != b"\0asm" { - return Err(Error::parse_invalid_binary("Invalid WASM magic number")); - } - Ok(()) - } - } - } -} - use kiln_foundation::{ safe_memory::{SafeMemoryHandler, SafeSlice, SafeStack}, traits::BoundedCapacity, @@ -91,10 +15,8 @@ use kiln_foundation::{ budget_aware_provider::CrateId, }; -#[cfg(feature = "std")] use std::vec; -#[cfg(feature = "std")] use crate::{ component_traits::{ ComponentInstance, ComponentRuntime, @@ -104,14 +26,7 @@ use crate::{ prelude::*, }; -#[cfg(all(not(feature = "std"), not(feature = "std")))] -use crate::{ - component_traits::{ComponentType, ExternType, FuncType}, - prelude::*, -}; - /// Host function implementation -#[cfg(feature = "std")] struct HostFunctionImpl< F: Fn( &[kiln_foundation::Value], @@ -128,7 +43,6 @@ struct HostFunctionImpl< // TODO: ComponentHostFunction trait not yet defined - commented out temporarily /* -#[cfg(feature = "std")] impl< F: Fn( &[kiln_foundation::Value], @@ -165,7 +79,6 @@ struct LegacyHostFunctionImpl< verification_level: VerificationLevel, } -#[cfg(feature = "std")] impl< F: Fn(&[kiln_foundation::Value]) -> Result>> + 'static + Send + Sync, > ComponentHostFunction for LegacyHostFunctionImpl @@ -212,7 +125,6 @@ impl DefaultHostFunctionFactory { } } -#[cfg(feature = "std")] impl HostFunctionFactory for DefaultHostFunctionFactory { /// Create a function with the given name and type fn create_function(&self, _name: &str, ty: &FuncType) -> Result> { @@ -228,25 +140,14 @@ impl HostFunctionFactory for DefaultHostFunctionFactory { }), }; - #[cfg(feature = "std")] - { - Ok(Box::new(func_impl)) - } - #[cfg(all(not(feature = "std"), not(feature = "std")))] - { - // Binary std/no_std choice - Err(Error::runtime_execution_error("Host function creation not supported")) - } + Ok(Box::new(func_impl)) } } -#[cfg(feature = "std")] type HostFunctionMap = HashMap>; -#[cfg(feature = "std")] type HostFactoryVec = Vec>; /// An implementation of the ComponentRuntime interface -#[cfg(feature = "std")] pub struct ComponentRuntimeImpl { /// Host function factories for creating host functions host_factories: HostFactoryVec, @@ -256,25 +157,17 @@ pub struct ComponentRuntimeImpl { host_functions: HostFunctionMap, } -#[cfg(feature = "std")] impl ComponentRuntime for ComponentRuntimeImpl { /// Create a new ComponentRuntimeImpl fn new() -> Self { Self { - #[cfg(feature = "std")] host_factories: Vec::with_capacity(8), - #[cfg(all(not(feature = "std"), not(feature = "std")))] - host_factories: HostFactoryVec::new(kiln_provider!(131072, CrateId::Runtime).unwrap_or_default()).expect("Failed to create host factories"), verification_level: VerificationLevel::default(), - #[cfg(feature = "std")] host_functions: HostFunctionMap::new(), - #[cfg(all(not(feature = "std"), not(feature = "std")))] - host_functions: HostFunctionMap::new(kiln_provider!(131072, CrateId::Runtime).unwrap_or_default()).expect("Failed to create host functions"), } } /// Register a host function factory - #[cfg(feature = "std")] fn register_host_factory(&mut self, factory: Box) { // Safety-enhanced push operation with verification if self.verification_level.should_verify(128) { @@ -282,20 +175,8 @@ impl ComponentRuntime for ComponentRuntimeImpl { self.verify_integrity().expect("ComponentRuntime integrity check failed"); } - #[cfg(feature = "std")] - { - // Push to Vec (can't use SafeStack since HostFunctionFactory doesn't implement Clone) - self.host_factories.push(factory); - } - - #[cfg(all(not(feature = "std"), not(feature = "std")))] - { - // Binary std/no_std choice - let _factory_id = self.host_factories.len() as u32; - let _ = self.host_factories.push(_factory_id); - // We don't actually store the factory in no_std mode for simplicity - core::mem::drop(factory); - } + // Push to Vec (can't use SafeStack since HostFunctionFactory doesn't implement Clone) + self.host_factories.push(factory); if self.verification_level.should_verify(128) { // Perform post-push integrity verification @@ -303,9 +184,7 @@ impl ComponentRuntime for ComponentRuntimeImpl { } } - /// Instantiate a component - #[cfg(feature = "std")] fn instantiate(&self, component_type: &ComponentType) -> Result> { // Verify integrity before instantiation if high verification level if self.verification_level.should_verify(200) { @@ -314,22 +193,10 @@ impl ComponentRuntime for ComponentRuntimeImpl { // Initialize memory with enough space (1 page = 64KB) let memory_size = 65536; - #[cfg(feature = "std")] let memory_data = vec![0; memory_size]; - #[cfg(all(not(feature = "std"), not(feature = "std")))] - let memory_data = { - let mut data = kiln_foundation::bounded::BoundedVec::new(); - for _ in 0..memory_size.min(65536) { - data.push(0u8).unwrap(); - } - data - }; // Collect host function names and types for tracking - #[cfg(feature = "std")] let mut host_function_names = Vec::new(); - #[cfg(all(not(feature = "std"), not(feature = "std")))] - let mut host_function_names = kiln_foundation::bounded::BoundedVec::new(); let mut host_functions = { let mut map = HashMap::new(); @@ -345,35 +212,16 @@ impl ComponentRuntime for ComponentRuntimeImpl { map }; - #[cfg(all(not(feature = "std"), not(feature = "std")))] - let host_functions = { - // Binary std/no_std choice - for (name, _id) in self.host_functions.iter() { - host_function_names.push(name.clone()); - } - // Return empty map-like structure for no_std - () - }; - // Create a basic component instance implementation - #[cfg(feature = "std")] - { - Ok(Box::new(ComponentInstanceImpl { - component_type: component_type.clone(), - verification_level: self.verification_level, - memory_store: kiln_foundation::safe_memory::SafeMemoryHandler::>::new(kiln_provider!(131072, CrateId::Runtime).unwrap_or_default()), - host_function_names, - host_functions, - })) - } - #[cfg(all(not(feature = "std"), not(feature = "std")))] - { - // Binary std/no_std choice - Err(Error::runtime_execution_error("Component instantiation not supported in no std mode")) - } + Ok(Box::new(ComponentInstanceImpl { + component_type: component_type.clone(), + verification_level: self.verification_level, + memory_store: kiln_foundation::safe_memory::SafeMemoryHandler::>::new(kiln_provider!(131072, CrateId::Runtime).unwrap_or_default()), + host_function_names, + host_functions, + })) } - /// Register a host function fn register_host_function(&mut self, name: &str, ty: FuncType, function: F) -> Result<()> where @@ -382,25 +230,17 @@ impl ComponentRuntime for ComponentRuntimeImpl { + Send + Sync, { - #[cfg(feature = "std")] - { - // Create a legacy host function implementation - let func_impl = LegacyHostFunctionImpl { - func_type: ty, - implementation: Arc::new(function), - verification_level: self.verification_level, - }; + // Create a legacy host function implementation + let func_impl = LegacyHostFunctionImpl { + func_type: ty, + implementation: Arc::new(function), + verification_level: self.verification_level, + }; - // Insert the function into the host functions map - let name_string = name.to_string(); + // Insert the function into the host functions map + let name_string = name.to_string(); - self.host_functions.insert(name_string, Box::new(func_impl)); - } - #[cfg(all(not(feature = "std"), not(feature = "std")))] - { - // Binary std/no_std choice - let _ = (name, ty, function); - } + self.host_functions.insert(name_string, Box::new(func_impl)); Ok(()) } @@ -417,7 +257,6 @@ impl ComponentRuntime for ComponentRuntimeImpl { } } -#[cfg(feature = "std")] impl ComponentRuntimeImpl { /// Create a new ComponentRuntimeImpl with a specific verification level /// @@ -464,7 +303,6 @@ struct ComponentInstanceImpl { host_functions: HostFunctionTypeMap, } -#[cfg(feature = "std")] impl ComponentInstance for ComponentInstanceImpl { /// Execute a function by name fn execute_function( @@ -629,7 +467,6 @@ mod tests { } } - #[cfg(feature = "std")] impl HostFunctionFactory for TestHostFunctionFactory { fn create_function( &self, @@ -665,7 +502,6 @@ mod tests { // A legacy host function for testing - returns Vec struct LegacyTestHostFunctionFactory; - #[cfg(feature = "std")] impl HostFunctionFactory for LegacyTestHostFunctionFactory { fn create_function( &self, diff --git a/kiln-runtime/src/component_traits.rs b/kiln-runtime/src/component_traits.rs index 2482535c..4252a689 100644 --- a/kiln-runtime/src/component_traits.rs +++ b/kiln-runtime/src/component_traits.rs @@ -11,7 +11,6 @@ pub type SafeStackValue = kiln_foundation::safe_memory::SafeStack Result; @@ -29,7 +28,6 @@ pub trait ComponentInstance { } /// Represents a host function implementation -#[cfg(feature = "std")] pub trait HostFunction { /// Call the host function with the given arguments fn call(&self, args: &[Value]) -> Result; @@ -40,18 +38,15 @@ pub trait HostFunction { } /// Represents a host function factory -#[cfg(feature = "std")] pub trait HostFunctionFactory { /// Create a host function implementation fn create_function(&self, name: &str, ty: &FuncType) -> Result>; } // Re-export HostImportHandler from kiln-foundation for convenience -#[cfg(feature = "std")] pub use kiln_foundation::HostImportHandler; /// Represents a component runtime environment -#[cfg(feature = "std")] pub trait ComponentRuntime { /// Create a new runtime instance fn new() -> Self diff --git a/kiln-runtime/src/component_unified.rs b/kiln-runtime/src/component_unified.rs index 684b5d17..15122f16 100644 --- a/kiln-runtime/src/component_unified.rs +++ b/kiln-runtime/src/component_unified.rs @@ -4,12 +4,6 @@ //! platform-aware memory system and resolve type conflicts between different //! runtime components. -// alloc is imported in lib.rs with proper feature gates - -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::boxed::Box; -// Import Box for no_std compatibility -#[cfg(feature = "std")] use alloc::boxed::Box; use kiln_error::{ @@ -29,8 +23,6 @@ use kiln_foundation::{ }, }; -#[cfg(not(any(feature = "std", feature = "alloc")))] -use crate::unified_types::PlatformMemoryAdapter as GenericMemoryAdapter; use crate::{ bounded_runtime_infra::{ create_runtime_provider, @@ -94,11 +86,6 @@ where pub component_type: ComponentType, /// Memory adapter for this component's allocations - #[cfg(any(feature = "std", feature = "alloc"))] - pub memory_adapter: PlatformMemoryAdapter, - - /// Memory adapter for this component's allocations (no_std version) - #[cfg(not(any(feature = "std", feature = "alloc")))] pub memory_adapter: PlatformMemoryAdapter, /// Exported functions and types from this component @@ -268,12 +255,7 @@ where /// Create a new component instance pub fn new( component_type: ComponentType, - #[cfg(any(feature = "std", feature = "alloc"))] memory_adapter: PlatformMemoryAdapter< - DefaultRuntimeProvider, - >, - #[cfg(not(any(feature = "std", feature = "alloc")))] memory_adapter: PlatformMemoryAdapter< - DefaultRuntimeProvider, - >, + memory_adapter: PlatformMemoryAdapter, ) -> Result { let exports = ExportMap::new(create_runtime_provider()?)?; let imports = ImportMap::new(create_runtime_provider()?)?; @@ -354,12 +336,7 @@ where Provider: MemoryProvider + Default + Clone + PartialEq + Eq, { /// Collection of active component instances - /// Using Vec because BoundedVec stores serialized data and can't return - /// references - #[cfg(any(feature = "std", feature = "alloc"))] instances: Vec>, - #[cfg(not(any(feature = "std", feature = "alloc")))] - instances: BoundedVec, 32, DefaultRuntimeProvider>, /// Platform-specific limits and configuration #[cfg(feature = "comprehensive-limits")] @@ -369,10 +346,6 @@ where memory_budget: ComponentMemoryBudget, /// Global memory adapter for cross-component resources - #[cfg(any(feature = "std", feature = "alloc"))] - global_memory_adapter: PlatformMemoryAdapter, - - #[cfg(not(any(feature = "std", feature = "alloc")))] global_memory_adapter: PlatformMemoryAdapter, } @@ -390,10 +363,7 @@ where .map_err(|_| Error::memory_error("Failed to create memory adapter"))?; Ok(Self { - #[cfg(any(feature = "std", feature = "alloc"))] instances: Vec::new(), - #[cfg(not(any(feature = "std", feature = "alloc")))] - instances: BoundedVec::new(create_runtime_provider()?)?, platform_limits: limits, memory_budget, global_memory_adapter, @@ -408,10 +378,7 @@ where .map_err(|_| Error::memory_error("Failed to create memory adapter"))?; // 64MB default Ok(Self { - #[cfg(any(feature = "std", feature = "alloc"))] instances: Vec::new(), - #[cfg(not(any(feature = "std", feature = "alloc")))] - instances: BoundedVec::new(create_runtime_provider()?)?, memory_budget, global_memory_adapter, }) @@ -464,15 +431,7 @@ where /// Get a reference to a component instance pub fn get_instance(&self, id: ComponentId) -> Option<&UnifiedComponentInstance> { - #[cfg(any(feature = "std", feature = "alloc"))] - return self.instances.iter().find(|instance| instance.id == id); - - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - // BoundedVec stores serialized data, so we can't return references - // This is a limitation of the no_std implementation - None - } + self.instances.iter().find(|instance| instance.id == id) } /// Get a mutable reference to a component instance @@ -480,15 +439,7 @@ where &mut self, id: ComponentId, ) -> Option<&mut UnifiedComponentInstance> { - #[cfg(any(feature = "std", feature = "alloc"))] - return self.instances.iter_mut().find(|instance| instance.id == id); - - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - // BoundedVec stores serialized data, so we can't return mutable references - // This is a limitation of the no_std implementation - None - } + self.instances.iter_mut().find(|instance| instance.id == id) } /// Get the number of active component instances diff --git a/kiln-runtime/src/engine/capability_engine.rs b/kiln-runtime/src/engine/capability_engine.rs index cd01ab90..b57bb843 100644 --- a/kiln-runtime/src/engine/capability_engine.rs +++ b/kiln-runtime/src/engine/capability_engine.rs @@ -8,14 +8,11 @@ #[cfg(feature = "tracing")] use kiln_foundation::tracing::{debug, trace, warn}; -#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::sync::Arc; use core::sync::atomic::{ AtomicU32, Ordering, }; -#[cfg(feature = "std")] -use alloc::sync::Arc; // Import decoder function use kiln_decoder::decoder::decode_module; @@ -256,10 +253,8 @@ pub struct CapabilityAwareEngine { /// Bounded host integration manager for safety-critical environments host_manager: Option, /// Import links: module_handle -> (module::name -> ImportLink) - #[cfg(feature = "std")] import_links: std::collections::HashMap>, /// Instance handle to instance_idx mapping for cross-instance calls - #[cfg(feature = "std")] handle_to_idx: std::collections::HashMap, } @@ -299,7 +294,6 @@ impl CapabilityAwareEngine { let mut inner_engine = StacklessEngine::new(); // Pass the host registry to the inner engine if available - #[cfg(feature = "std")] if let Some(ref registry) = host_registry { use std::sync::Arc as StdArc; inner_engine.set_host_registry(StdArc::new(registry.clone())); @@ -314,9 +308,7 @@ impl CapabilityAwareEngine { next_instance_idx: 0, host_registry, host_manager, - #[cfg(feature = "std")] import_links: std::collections::HashMap::new(), - #[cfg(feature = "std")] handle_to_idx: std::collections::HashMap::new(), }) } @@ -325,7 +317,6 @@ impl CapabilityAwareEngine { /// /// This allows updating the registry after engine creation, which is needed /// for component model instantiation where the registry is created separately. - #[cfg(feature = "std")] pub fn set_host_registry(&mut self, registry: std::sync::Arc) { self.host_registry = Some((*registry).clone()); self.inner.set_host_registry(registry); @@ -336,7 +327,6 @@ impl CapabilityAwareEngine { /// This handler will be used for ALL host function calls including WASI. /// The engine has no knowledge of specific host interfaces - it delegates /// all import resolution to this handler. - #[cfg(feature = "std")] pub fn set_host_handler(&mut self, handler: Box) { self.inner.set_host_handler(handler); } @@ -499,7 +489,6 @@ impl CapabilityAwareEngine { /// When a module calls a function at this (instance_id, func_idx), the engine /// will dispatch to the canonical executor instead of executing bytecode. /// This prevents infinite recursion in shim modules with self-referential tables. - #[cfg(feature = "std")] pub fn register_lowered_function( &mut self, instance_id: usize, @@ -557,7 +546,6 @@ impl CapabilityEngine for CapabilityAwareEngine { ); // Debug: list all exports - #[cfg(feature = "std")] #[cfg(feature = "tracing")] { let elem_count = runtime_module.elements.len(); @@ -579,7 +567,6 @@ impl CapabilityEngine for CapabilityAwareEngine { } // TODO: Initialize data segments into memory - // #[cfg(feature = "std")] // runtime_module.initialize_data_segments()?; // Stack pointer is now initialized early during global creation in from_kiln_module() @@ -635,13 +622,11 @@ impl CapabilityEngine for CapabilityAwareEngine { // Get pending import links EARLY - we need to apply table/memory/global imports // BEFORE element segment initialization - #[cfg(feature = "std")] let pending_links = self.import_links.get(&module_handle).cloned(); // CRITICAL: Apply table/memory/global imports BEFORE element segments! // Tables must be available before element segments try to populate them. // Function imports can be applied later (resolved at call time). - #[cfg(feature = "std")] if let Some(ref links) = pending_links { for (import_key, link) in links { match link.import_kind { @@ -722,19 +707,13 @@ impl CapabilityEngine for CapabilityAwareEngine { } // Initialize data segments into instance memory (critical for static data!) - #[cfg(feature = "std")] - { - #[cfg(feature = "tracing")] - debug!("Initializing data segments..."); - instance.initialize_data_segments()?; - } + #[cfg(feature = "tracing")] + debug!("Initializing data segments..."); + instance.initialize_data_segments()?; // Initialize element segments into tables (critical for call_indirect!) // IMPORTANT: This MUST come AFTER table imports are applied above - #[cfg(feature = "std")] - { - instance.initialize_element_segments()?; - } + instance.initialize_element_segments()?; // Don't clone! Cloning creates a fresh empty instance, losing all our populate work let instance_arc = Arc::new(instance); @@ -748,11 +727,9 @@ impl CapabilityEngine for CapabilityAwareEngine { self.instances.insert(handle, instance_arc)?; // Store handle -> instance_idx mapping for cross-instance calls - #[cfg(feature = "std")] self.handle_to_idx.insert(handle, instance_idx); // Register FUNCTION import links with the inner engine (for call-time resolution) - #[cfg(feature = "std")] if let Some(links) = pending_links { #[cfg(feature = "tracing")] trace!( @@ -817,7 +794,6 @@ impl CapabilityEngine for CapabilityAwareEngine { Ok(handle) } - #[cfg(feature = "std")] fn link_import( &mut self, module: ModuleHandle, @@ -837,16 +813,13 @@ impl CapabilityEngine for CapabilityAwareEngine { // Add to inner StacklessEngine's import_links // Key: (instance_id, import_module, import_name) // Value: (target_instance_id, export_name) - #[cfg(feature = "std")] - { - self.inner.add_import_link( - module_id, - import_module.to_string(), - import_name.to_string(), - provider_id, - export_name.to_string(), - ); - } + self.inner.add_import_link( + module_id, + import_module.to_string(), + import_name.to_string(), + provider_id, + export_name.to_string(), + ); // Also store in our own links map for tracking let import_key = if import_module.is_empty() { @@ -917,72 +890,69 @@ impl CapabilityEngine for CapabilityAwareEngine { // Check if this is a directly callable host function by name // This allows test code to directly invoke WASI functions - #[cfg(feature = "std")] - { - // Try to split func_name into module::function format - if func_name.contains("::") { - let parts: Vec<&str> = func_name.split("::").collect(); - if parts.len() >= 2 { - let module_str = parts[0]; - let func_str = parts[1..].join("::"); - - if let Some(ref registry) = self.host_registry { - if registry.has_host_function(module_str, &func_str) { - #[cfg(feature = "tracing")] - trace!( - module = module_str, - function = func_str, - "Direct call to host function" - ); - - let mut dummy_engine = (); - let results = registry.call_host_function( - &mut dummy_engine as &mut dyn core::any::Any, - module_str, - &func_str, - args.to_vec() - )?; - - #[cfg(feature = "tracing")] - trace!(result_count = results.len(), "Host function returned"); - return Ok(results); - } + // Try to split func_name into module::function format + if func_name.contains("::") { + let parts: Vec<&str> = func_name.split("::").collect(); + if parts.len() >= 2 { + let module_str = parts[0]; + let func_str = parts[1..].join("::"); + + if let Some(ref registry) = self.host_registry { + if registry.has_host_function(module_str, &func_str) { + #[cfg(feature = "tracing")] + trace!( + module = module_str, + function = func_str, + "Direct call to host function" + ); + + let mut dummy_engine = (); + let results = registry.call_host_function( + &mut dummy_engine as &mut dyn core::any::Any, + module_str, + &func_str, + args.to_vec() + )?; + + #[cfg(feature = "tracing")] + trace!(result_count = results.len(), "Host function returned"); + return Ok(results); } } } + } - // Also try wasi: prefix format like "wasi:cli/stdout@0.2.0" - // BUT ONLY if this function is NOT exported by the module! - // If the module exports it (like wasi:cli/run@0.2.3#run), we should call - // the module's implementation, not dispatch to host. - let is_module_export = instance.module().find_function_by_name(func_name).is_some(); - if func_name.starts_with("wasi:") && !is_module_export { - // Extract just the function name part (last component after #) - if let Some(hash_pos) = func_name.rfind('#') { - let module_part = &func_name[..hash_pos]; - let func_part = &func_name[hash_pos+1..]; - - if let Some(ref registry) = self.host_registry { - if registry.has_host_function(module_part, func_part) { - #[cfg(feature = "tracing")] - trace!( - module = module_part, - function = func_part, - "WASI host function call" - ); - - let mut dummy_engine = (); - let results = registry.call_host_function( - &mut dummy_engine as &mut dyn core::any::Any, - module_part, - func_part, - args.to_vec() - )?; - - #[cfg(feature = "tracing")] - trace!(result_count = results.len(), "Host function returned"); - return Ok(results); - } + // Also try wasi: prefix format like "wasi:cli/stdout@0.2.0" + // BUT ONLY if this function is NOT exported by the module! + // If the module exports it (like wasi:cli/run@0.2.3#run), we should call + // the module's implementation, not dispatch to host. + let is_module_export = instance.module().find_function_by_name(func_name).is_some(); + if func_name.starts_with("wasi:") && !is_module_export { + // Extract just the function name part (last component after #) + if let Some(hash_pos) = func_name.rfind('#') { + let module_part = &func_name[..hash_pos]; + let func_part = &func_name[hash_pos+1..]; + + if let Some(ref registry) = self.host_registry { + if registry.has_host_function(module_part, func_part) { + #[cfg(feature = "tracing")] + trace!( + module = module_part, + function = func_part, + "WASI host function call" + ); + + let mut dummy_engine = (); + let results = registry.call_host_function( + &mut dummy_engine as &mut dyn core::any::Any, + module_part, + func_part, + args.to_vec() + )?; + + #[cfg(feature = "tracing")] + trace!(result_count = results.len(), "Host function returned"); + return Ok(results); } } } @@ -1088,7 +1058,6 @@ impl CapabilityAwareEngine { /// Determine the kind of import (function, table, memory, global) from the module's import /// declarations - #[cfg(feature = "std")] fn determine_import_kind( &self, module_handle: ModuleHandle, diff --git a/kiln-runtime/src/engine_factory.rs b/kiln-runtime/src/engine_factory.rs index 15a1a88f..96a7ef73 100644 --- a/kiln-runtime/src/engine_factory.rs +++ b/kiln-runtime/src/engine_factory.rs @@ -4,13 +4,6 @@ //! WebAssembly engines with clear separation of concerns and configurable //! capabilities. -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::{ - boxed::Box, - vec, - vec::Vec, -}; -#[cfg(feature = "std")] use alloc::{ boxed::Box, vec, @@ -179,7 +172,6 @@ impl EngineFactory { } /// Create a preconfigured WAST testing engine - #[cfg(feature = "std")] pub fn wast_testing() -> Result> { Self::create( EngineConfig::new(EngineType::Wast) @@ -207,7 +199,6 @@ pub trait RuntimeEngine { fn get_statistics(&self) -> EngineStatistics; /// Set the host function registry for imported function calls - #[cfg(feature = "std")] fn set_host_registry(&mut self, registry: std::sync::Arc); } @@ -235,7 +226,6 @@ impl RuntimeEngine for crate::stackless::StacklessEngine { EngineStatistics::default() } - #[cfg(feature = "std")] fn set_host_registry(&mut self, registry: std::sync::Arc) { self.set_host_registry(registry); } diff --git a/kiln-runtime/src/execution.rs b/kiln-runtime/src/execution.rs index dde8cda2..064cb9cd 100644 --- a/kiln-runtime/src/execution.rs +++ b/kiln-runtime/src/execution.rs @@ -17,12 +17,6 @@ //! All execution operations are bounds-checked and memory-safe, preventing //! stack overflows and maintaining WebAssembly's sandboxing guarantees. -// alloc is imported in lib.rs with proper feature gates - -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::format; -// Import format! macro for string formatting -#[cfg(feature = "std")] use std::format; use crate::prelude::{ diff --git a/kiln-runtime/src/format_bridge.rs b/kiln-runtime/src/format_bridge.rs index 22f3b611..13896efa 100644 --- a/kiln-runtime/src/format_bridge.rs +++ b/kiln-runtime/src/format_bridge.rs @@ -4,11 +4,6 @@ //! kiln-format and converting it to runtime representations. It establishes //! the runtime side of the boundary between format and runtime layers. -// alloc is imported in lib.rs with proper feature gates - -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::vec::Vec; -#[cfg(feature = "std")] use alloc::vec::Vec; use kiln_foundation::{ @@ -23,9 +18,6 @@ use kiln_foundation::{ }; use crate::prelude::*; -// For no_std without alloc, use type aliases with concrete providers -#[cfg(not(any(feature = "std", feature = "alloc")))] -type Vec = kiln_foundation::BoundedVec>; /// Trait for types that can be initialized from format representations pub trait FromFormatBridge { @@ -167,7 +159,6 @@ pub enum RuntimeRefType { ExternRef, } - impl Checksummable for RuntimeRefType { fn update_checksum(&self, checksum: &mut kiln_foundation::verification::Checksum) { let discriminant = match self { @@ -256,16 +247,7 @@ impl Default for RuntimeDataSegment { index: 0, memory_index: None, evaluated_offset: None, - data: { - #[cfg(any(feature = "std", feature = "alloc"))] - { - Vec::new() - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - kiln_foundation::BoundedVec::new(kiln_foundation::NoStdProvider::<1024>::default()).unwrap_or_default() - } - }, + data: Vec::new(), initialization_state: InitializationState::Pending, runtime_handle: 0, } @@ -304,10 +286,7 @@ impl ToBytes for RuntimeDataSegment { self.evaluated_offset.to_bytes_with_provider(writer, provider)?; (self.data.len() as u32).to_bytes_with_provider(writer, provider)?; for byte in &self.data { - #[cfg(any(feature = "std", feature = "alloc"))] writer.write_u8(*byte)?; - #[cfg(not(any(feature = "std", feature = "alloc")))] - writer.write_u8(byte)?; } self.initialization_state.to_bytes_with_provider(writer, provider)?; self.runtime_handle.to_bytes_with_provider(writer, provider)?; @@ -326,26 +305,11 @@ impl FromBytes for RuntimeDataSegment { let data_len = u32::from_bytes_with_provider(reader, provider)? as usize; let data = { - #[cfg(any(feature = "std", feature = "alloc"))] - { - let mut vec = Vec::with_capacity(data_len); - for _ in 0..data_len { - vec.push(reader.read_u8()?); - } - vec - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - let data_provider = kiln_foundation::NoStdProvider::<1024>::default(); - let mut vec = kiln_foundation::BoundedVec::new(data_provider) - .map_err(|_| Error::parse_error("Failed to create data vector"))?; - for _ in 0..data_len { - vec.push(reader.read_u8()?).map_err(|_| { - Error::parse_error("Data segment too large for bounded vector") - })?; - } - vec + let mut vec = Vec::with_capacity(data_len); + for _ in 0..data_len { + vec.push(reader.read_u8()?); } + vec }; let initialization_state = InitializationState::from_bytes_with_provider(reader, provider)?; @@ -385,16 +349,7 @@ impl Default for RuntimeElementSegment { index: 0, table_index: None, evaluated_offset: None, - elements: { - #[cfg(any(feature = "std", feature = "alloc"))] - { - Vec::new() - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - kiln_foundation::BoundedVec::new(kiln_foundation::NoStdProvider::<1024>::default()).unwrap_or_default() - } - }, + elements: Vec::new(), initialization_state: InitializationState::Pending, runtime_handle: 0, } @@ -445,26 +400,11 @@ impl FromBytes for RuntimeElementSegment { let elements_len = u32::from_bytes_with_provider(reader, provider)? as usize; let elements = { - #[cfg(any(feature = "std", feature = "alloc"))] - { - let mut vec = Vec::with_capacity(elements_len); - for _ in 0..elements_len { - vec.push(RuntimeElement::from_bytes_with_provider(reader, provider)?); - } - vec - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - let elements_provider = kiln_foundation::NoStdProvider::<1024>::default(); - let mut vec = kiln_foundation::BoundedVec::new(elements_provider) - .map_err(|_| Error::parse_error("Failed to create elements vector"))?; - for _ in 0..elements_len { - vec.push(RuntimeElement::from_bytes_with_provider(reader, provider)?).map_err( - |_| Error::parse_error("Element segment too large for bounded vector"), - )?; - } - vec + let mut vec = Vec::with_capacity(elements_len); + for _ in 0..elements_len { + vec.push(RuntimeElement::from_bytes_with_provider(reader, provider)?); } + vec }; let initialization_state = InitializationState::from_bytes_with_provider(reader, provider)?; @@ -670,29 +610,13 @@ pub struct RuntimeModuleInitializer { impl RuntimeModuleInitializer { /// Create new initializer with runtime context pub fn new(context: RuntimeContext) -> Self { - #[cfg(any(feature = "std", feature = "alloc"))] - { - Self { - context, - data_segments: Vec::new(), - element_segments: Vec::new(), - start_function: None, - current_step: 0, - total_steps: 0, - } - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - let provider = kiln_foundation::NoStdProvider::<1024>::default(); - Self { - context, - data_segments: kiln_foundation::BoundedVec::new(provider.clone()) - .unwrap_or_default(), - element_segments: kiln_foundation::BoundedVec::new(provider).unwrap_or_default(), - start_function: None, - current_step: 0, - total_steps: 0, - } + Self { + context, + data_segments: Vec::new(), + element_segments: Vec::new(), + start_function: None, + current_step: 0, + total_steps: 0, } } @@ -728,24 +652,11 @@ impl RuntimeModuleInitializer { /// Execute initialization process pub fn execute_initialization(&mut self) -> Result<()> { // Initialize active data segments - use indices to avoid borrowing conflicts - #[cfg(any(feature = "std", feature = "alloc"))] let mut active_indices = Vec::new(); - #[cfg(not(any(feature = "std", feature = "alloc")))] - let mut active_indices = { - let provider = kiln_foundation::NoStdProvider::<1024>::default(); - Vec::new(provider).map_err(|_| { - Error::runtime_execution_error("Failed to create active indices vector") - })? - }; for (idx, segment) in self.data_segments.iter().enumerate() { if segment.memory_index.is_some() { - #[cfg(any(feature = "std", feature = "alloc"))] active_indices.push(idx); - #[cfg(not(any(feature = "std", feature = "alloc")))] - active_indices.push(idx).map_err(|_| { - Error::runtime_execution_error("Failed to add index to active indices") - })?; } } @@ -757,24 +668,11 @@ impl RuntimeModuleInitializer { } // Initialize active element segments - use indices to avoid borrowing conflicts - #[cfg(any(feature = "std", feature = "alloc"))] let mut active_element_indices = Vec::new(); - #[cfg(not(any(feature = "std", feature = "alloc")))] - let mut active_element_indices = { - let provider = kiln_foundation::NoStdProvider::<1024>::default(); - Vec::new(provider).map_err(|_| { - Error::runtime_execution_error("Failed to create active element indices vector") - })? - }; for (idx, segment) in self.element_segments.iter().enumerate() { if segment.table_index.is_some() { - #[cfg(any(feature = "std", feature = "alloc"))] active_element_indices.push(idx); - #[cfg(not(any(feature = "std", feature = "alloc")))] - active_element_indices.push(idx).map_err(|_| { - Error::runtime_execution_error("Failed to add index to active element indices") - })?; } } @@ -828,16 +726,7 @@ impl RuntimeModuleInitializer { index, memory_index: extraction.memory_index, evaluated_offset: None, // Will be computed during initialization - data: { - #[cfg(any(feature = "std", feature = "alloc"))] - { - Vec::new() - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - kiln_foundation::BoundedVec::new(kiln_foundation::NoStdProvider::<1024>::default()).unwrap_or_default() - } - }, + data: Vec::new(), initialization_state: InitializationState::Pending, runtime_handle: self.generate_runtime_handle(), }) @@ -853,16 +742,7 @@ impl RuntimeModuleInitializer { index, table_index: extraction.table_index, evaluated_offset: None, // Will be computed during initialization - elements: { - #[cfg(any(feature = "std", feature = "alloc"))] - { - Vec::new() - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - kiln_foundation::BoundedVec::new(kiln_foundation::NoStdProvider::<1024>::default()).unwrap_or_default() - } - }, + elements: Vec::new(), initialization_state: InitializationState::Pending, runtime_handle: self.generate_runtime_handle(), }) @@ -941,7 +821,6 @@ pub struct FormatDataExtraction { pub requires_initialization: bool, } - impl Checksummable for FormatDataExtraction { fn update_checksum(&self, checksum: &mut kiln_foundation::verification::Checksum) { self.memory_index.update_checksum(checksum); @@ -963,10 +842,7 @@ impl ToBytes for FormatDataExtraction { self.memory_index.to_bytes_with_provider(writer, provider)?; (self.offset_expr_bytes.len() as u32).to_bytes_with_provider(writer, provider)?; for byte in &self.offset_expr_bytes { - #[cfg(any(feature = "std", feature = "alloc"))] writer.write_u8(*byte)?; - #[cfg(not(any(feature = "std", feature = "alloc")))] - writer.write_u8(byte)?; } (self.data_size as u32).to_bytes_with_provider(writer, provider)?; self.requires_initialization.to_bytes_with_provider(writer, provider)?; @@ -983,26 +859,11 @@ impl FromBytes for FormatDataExtraction { let bytes_len = u32::from_bytes_with_provider(reader, provider)? as usize; let offset_expr_bytes = { - #[cfg(any(feature = "std", feature = "alloc"))] - { - let mut vec = Vec::with_capacity(bytes_len); - for _ in 0..bytes_len { - vec.push(reader.read_u8()?); - } - vec - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - let bytes_provider = kiln_foundation::NoStdProvider::<1024>::default(); - let mut vec = kiln_foundation::BoundedVec::new(bytes_provider) - .map_err(|_| Error::parse_error("Failed to create offset bytes vector"))?; - for _ in 0..bytes_len { - vec.push(reader.read_u8()?).map_err(|_| { - Error::parse_error("Offset expression too large for bounded vector") - })?; - } - vec + let mut vec = Vec::with_capacity(bytes_len); + for _ in 0..bytes_len { + vec.push(reader.read_u8()?); } + vec }; let data_size = u32::from_bytes_with_provider(reader, provider)? as usize; @@ -1034,16 +895,7 @@ impl Default for FormatElementExtraction { fn default() -> Self { Self { table_index: None, - offset_expr_bytes: { - #[cfg(any(feature = "std", feature = "alloc"))] - { - Vec::new() - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - kiln_foundation::BoundedVec::new(kiln_foundation::NoStdProvider::<1024>::default()).unwrap_or_default() - } - }, + offset_expr_bytes: Vec::new(), init_data_type: FormatElementInitType::FunctionIndices, requires_initialization: false, } @@ -1071,10 +923,7 @@ impl ToBytes for FormatElementExtraction { self.table_index.to_bytes_with_provider(writer, provider)?; (self.offset_expr_bytes.len() as u32).to_bytes_with_provider(writer, provider)?; for byte in &self.offset_expr_bytes { - #[cfg(any(feature = "std", feature = "alloc"))] writer.write_u8(*byte)?; - #[cfg(not(any(feature = "std", feature = "alloc")))] - writer.write_u8(byte)?; } self.init_data_type.to_bytes_with_provider(writer, provider)?; self.requires_initialization.to_bytes_with_provider(writer, provider)?; @@ -1091,26 +940,11 @@ impl FromBytes for FormatElementExtraction { let bytes_len = u32::from_bytes_with_provider(reader, provider)? as usize; let offset_expr_bytes = { - #[cfg(any(feature = "std", feature = "alloc"))] - { - let mut vec = Vec::with_capacity(bytes_len); - for _ in 0..bytes_len { - vec.push(reader.read_u8()?); - } - vec - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - let bytes_provider = kiln_foundation::NoStdProvider::<1024>::default(); - let mut vec = kiln_foundation::BoundedVec::new(bytes_provider) - .map_err(|_| Error::parse_error("Failed to create offset bytes vector"))?; - for _ in 0..bytes_len { - vec.push(reader.read_u8()?).map_err(|_| { - Error::parse_error("Offset expression too large for bounded vector") - })?; - } - vec + let mut vec = Vec::with_capacity(bytes_len); + for _ in 0..bytes_len { + vec.push(reader.read_u8()?); } + vec }; let init_data_type = FormatElementInitType::from_bytes_with_provider(reader, provider)?; @@ -1177,26 +1011,11 @@ impl FromBytes for FormatElementInitType { impl Default for RuntimeContext { fn default() -> Self { - #[cfg(any(feature = "std", feature = "alloc"))] - { - Self { - memory_providers: Vec::new(), - table_providers: Vec::new(), - max_initialization_steps: 1000, - asil_constraints: ASILConstraints::default(), - } - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - let provider = kiln_foundation::NoStdProvider::<1024>::default(); - Self { - memory_providers: kiln_foundation::BoundedVec::new(provider.clone()) - .unwrap_or_default(), - table_providers: kiln_foundation::BoundedVec::new(provider) - .unwrap_or_default(), - max_initialization_steps: 1000, - asil_constraints: ASILConstraints::default(), - } + Self { + memory_providers: Vec::new(), + table_providers: Vec::new(), + max_initialization_steps: 1000, + asil_constraints: ASILConstraints::default(), } } } diff --git a/kiln-runtime/src/global.rs b/kiln-runtime/src/global.rs index caee92c5..3aa2e429 100644 --- a/kiln-runtime/src/global.rs +++ b/kiln-runtime/src/global.rs @@ -2,13 +2,6 @@ //! //! This module provides the implementation for WebAssembly globals. -// Use KilnGlobalType directly from kiln_foundation, and KilnValueType, KilnValue -// alloc is imported in lib.rs with proper feature gates - -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::format; -// Import format! macro for string formatting -#[cfg(feature = "std")] use std::format; use kiln_foundation::{ diff --git a/kiln-runtime/src/memory_adapter.rs b/kiln-runtime/src/memory_adapter.rs index 9e624cb0..b7dd1391 100644 --- a/kiln-runtime/src/memory_adapter.rs +++ b/kiln-runtime/src/memory_adapter.rs @@ -6,15 +6,9 @@ // Use our prelude for consistent imports // alloc is imported in lib.rs with proper feature gates -// Import Arc from the correct location to match ArcMemoryExt -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::format; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::sync::Arc; // Import format! macro for string formatting -#[cfg(feature = "std")] use std::format; -#[cfg(feature = "std")] +// Import Arc from the correct location to match ArcMemoryExt use alloc::sync::Arc; use crate::{ diff --git a/kiln-runtime/src/memory_config_adapter.rs b/kiln-runtime/src/memory_config_adapter.rs index 1546b1a4..10638761 100644 --- a/kiln-runtime/src/memory_config_adapter.rs +++ b/kiln-runtime/src/memory_config_adapter.rs @@ -9,7 +9,6 @@ use kiln_error::{ Error, ErrorCategory, }; -#[cfg(any(feature = "std", feature = "alloc"))] use kiln_foundation::capabilities::{ factory::CapabilityGuardedProvider, MemoryCapabilityContext, @@ -29,12 +28,6 @@ use kiln_foundation::{ }; // Type alias for the provider type that works with BoundedVec -// In std/alloc environments, use CapabilityAwareProvider wrapper -#[cfg(any(feature = "std", feature = "alloc"))] -type AllocatedProvider = CapabilityAwareProvider>; - -// In no_std environments, also use CapabilityAwareProvider for consistency -#[cfg(not(any(feature = "std", feature = "alloc")))] type AllocatedProvider = CapabilityAwareProvider>; // Import provider creation functions from prelude which handles conditionals @@ -201,17 +194,7 @@ pub mod platform_types { /// Create a platform-aware memory provider for runtime operations pub fn create_platform_provider() -> Result> { - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - // For no_std, use safe allocation - let context = capability_context!(dynamic(CrateId::Runtime, 8192))?; - let provider = safe_capability_alloc!(context, CrateId::Runtime, 8192)?; - Ok(provider) - } - #[cfg(any(feature = "std", feature = "alloc"))] - { - MemoryFactory::create_wrapped::<8192>(CrateId::Runtime) - } + MemoryFactory::create_wrapped::<8192>(CrateId::Runtime) } } @@ -221,50 +204,17 @@ pub struct DynamicProviderFactory; impl DynamicProviderFactory { /// Create a provider sized for the current platform pub fn create_for_use_case(use_case: MemoryUseCase) -> Result> { - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - // For no_std, use safe allocation - let context = capability_context!(dynamic(CrateId::Runtime, 16384))?; - let provider = safe_capability_alloc!(context, CrateId::Runtime, 16384)?; - Ok(provider) - } - - #[cfg(any(feature = "std", feature = "alloc"))] - { - MemoryFactory::create_wrapped::<16384>(CrateId::Runtime) - } + MemoryFactory::create_wrapped::<16384>(CrateId::Runtime) } /// Create a string provider with platform-appropriate size pub fn create_string_provider() -> Result> { - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - // For no_std, use safe allocation - let context = capability_context!(dynamic(CrateId::Runtime, 8192))?; - let provider = safe_capability_alloc!(context, CrateId::Runtime, 8192)?; - Ok(provider) - } - - #[cfg(any(feature = "std", feature = "alloc"))] - { - MemoryFactory::create_wrapped::<8192>(CrateId::Runtime) - } + MemoryFactory::create_wrapped::<8192>(CrateId::Runtime) } /// Create a collection provider with platform-appropriate size pub fn create_collection_provider() -> Result> { - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - // For no_std, use safe allocation - let context = capability_context!(dynamic(CrateId::Runtime, 16384))?; - let provider = safe_capability_alloc!(context, CrateId::Runtime, 16384)?; - Ok(provider) - } - - #[cfg(any(feature = "std", feature = "alloc"))] - { - MemoryFactory::create_wrapped::<16384>(CrateId::Runtime) - } + MemoryFactory::create_wrapped::<16384>(CrateId::Runtime) } } diff --git a/kiln-runtime/src/module_builder.rs b/kiln-runtime/src/module_builder.rs index 9a6d9b4f..1ba1cc08 100644 --- a/kiln-runtime/src/module_builder.rs +++ b/kiln-runtime/src/module_builder.rs @@ -6,17 +6,9 @@ // Decoder imports are optional during development // use kiln_decoder::{module::CodeSection, -// runtime_adapter::RuntimeModuleBuilder}; alloc is imported in lib.rs with -// proper feature gates +// runtime_adapter::RuntimeModuleBuilder}; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::format; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::vec::Vec; -// Import format! macro for string formatting -#[cfg(feature = "std")] use std::format; -#[cfg(feature = "std")] use alloc::vec::Vec; use kiln_format::{ @@ -399,7 +391,6 @@ impl ModuleBuilder { } /// Sets the binary representation of the module. - #[cfg(any(feature = "std", feature = "alloc"))] pub fn set_binary(&mut self, _binary: Vec) -> Result<()> { Ok(()) } diff --git a/kiln-runtime/src/multi_memory.rs b/kiln-runtime/src/multi_memory.rs index 1ab1d54b..ca9ff66b 100644 --- a/kiln-runtime/src/multi_memory.rs +++ b/kiln-runtime/src/multi_memory.rs @@ -309,7 +309,6 @@ impl MultiMemoryInstance { #[derive(Debug)] pub struct MultiMemoryContext { /// Memory instances indexed by memory index. - #[cfg(feature = "std")] memories: HashMap>, /// Thread-safe counter for memory allocation. diff --git a/kiln-runtime/src/platform_runtime.rs b/kiln-runtime/src/platform_runtime.rs index e10eface..de07b0f7 100644 --- a/kiln-runtime/src/platform_runtime.rs +++ b/kiln-runtime/src/platform_runtime.rs @@ -14,25 +14,13 @@ #![allow(clippy::module_name_repetitions)] -// alloc is imported in lib.rs with proper feature gates -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::{ - boxed::Box, - vec, - vec::Vec, -}; // Import Box, Vec, and other types for allocating memory adapters -#[cfg(feature = "std")] use alloc::{ boxed::Box, vec, vec::Vec, }; -// For no_std without alloc, use BoundedVec instead of Vec -#[cfg(not(any(feature = "std", feature = "alloc")))] -use kiln_foundation::bounded::BoundedVec; - use crate::{ cfi_engine::{ CfiExecutionEngine, @@ -50,14 +38,8 @@ use crate::{ prelude::*, unified_types::UnifiedMemoryAdapter as UnifiedMemoryAdapterTrait, }; -#[cfg(not(any(feature = "std", feature = "alloc")))] -type PlatformVec = BoundedVec>; - // Type alias for Vec that works in all feature configurations -#[cfg(any(feature = "std", feature = "alloc"))] type ValueVec = Vec; -#[cfg(not(any(feature = "std", feature = "alloc")))] -type ValueVec = PlatformVec; // Import Value type use kiln_error::{ @@ -74,7 +56,6 @@ use kiln_platform::MacOsAllocatorBuilder; #[cfg(all(feature = "platform-qnx", target_os = "nto"))] use kiln_platform::QnxAllocatorBuilder; // Import from kiln-platform for all platform abstractions -#[cfg(feature = "std")] use kiln_platform::{ ComprehensivePlatformLimits, PageAllocator, @@ -88,7 +69,6 @@ use kiln_platform::{ use crate::cfi_engine::CfiControlFlowProtection; // Helper function to convert between ASIL level types -#[cfg(feature = "std")] fn convert_asil_level(platform_asil: kiln_platform::AsilLevel) -> AsilLevel { match platform_asil { kiln_platform::AsilLevel::QM => AsilLevel::QM, @@ -106,10 +86,9 @@ pub struct PlatformAwareRuntime { /// Execution engine with CFI protection execution_engine: CfiExecutionEngine, /// Platform-specific memory allocator - #[cfg(all(any(feature = "std", feature = "alloc"), feature = "platform"))] + #[cfg(feature = "platform")] memory_allocator: Box, /// Platform-specific limits and capabilities - #[cfg(feature = "std")] platform_limits: ComprehensivePlatformLimits, /// Safety context for ASIL compliance safety_context: SafetyContext, @@ -146,7 +125,7 @@ impl PlatformAwareRuntime { /// Create new platform-aware runtime with specific limits pub fn new_with_limits(limits: ComprehensivePlatformLimits) -> Result { - #[cfg(all(any(feature = "std", feature = "alloc"), feature = "platform"))] + #[cfg(feature = "platform")] let memory_allocator = Self::create_memory_allocator(&limits)?; let cfi_protection = Self::create_cfi_protection(&limits); @@ -155,7 +134,7 @@ impl PlatformAwareRuntime { Ok(Self { execution_engine, - #[cfg(all(any(feature = "std", feature = "alloc"), feature = "platform"))] + #[cfg(feature = "platform")] memory_allocator, platform_limits: limits, safety_context, @@ -164,12 +143,11 @@ impl PlatformAwareRuntime { } /// Create runtime with custom CFI violation policy - #[cfg(feature = "std")] pub fn new_with_cfi_policy( limits: ComprehensivePlatformLimits, cfi_policy: CfiViolationPolicy, ) -> Result { - #[cfg(all(any(feature = "std", feature = "alloc"), feature = "platform"))] + #[cfg(feature = "platform")] let memory_allocator = Self::create_memory_allocator(&limits)?; let cfi_protection = Self::create_cfi_protection(&limits); @@ -178,7 +156,7 @@ impl PlatformAwareRuntime { Ok(Self { execution_engine, - #[cfg(all(any(feature = "std", feature = "alloc"), feature = "platform"))] + #[cfg(feature = "platform")] memory_allocator, platform_limits: limits, safety_context, @@ -195,7 +173,6 @@ impl PlatformAwareRuntime { let start_time = self.get_timestamp(); // Validate execution against platform limits - #[cfg(feature = "std")] self.validate_execution_limits(function, args)?; // Create execution context with platform limits @@ -273,7 +250,7 @@ impl PlatformAwareRuntime { } /// Create platform-specific memory allocator using kiln-platform - #[cfg(all(any(feature = "std", feature = "alloc"), feature = "platform"))] + #[cfg(feature = "platform")] fn create_memory_allocator( limits: &ComprehensivePlatformLimits, ) -> Result> { @@ -359,7 +336,6 @@ impl PlatformAwareRuntime { // No-std environments use NoStdProvider from kiln-platform /// Create CFI protection configuration based on platform capabilities - #[cfg(feature = "std")] fn create_cfi_protection(limits: &ComprehensivePlatformLimits) -> CfiControlFlowProtection { let protection_level = match convert_asil_level(limits.asil_level) { AsilLevel::QM => 0, // Basic protection level @@ -414,7 +390,6 @@ impl PlatformAwareRuntime { } /// Update memory usage metrics - #[cfg(feature = "std")] fn update_memory_metrics(&mut self) { let current_usage = self.total_memory() - self.available_memory(); self.metrics.memory_allocated = current_usage; @@ -430,43 +405,19 @@ impl PlatformAwareRuntime { _arg_count: usize, ) -> Result { // Simplified implementation - in real scenario this would extract actual values - #[cfg(any(feature = "std", feature = "alloc"))] - { - use kiln_foundation::{ - budget_aware_provider::CrateId, - capability_allocators::capability_alloc::capability_vec, - memory_init::get_global_capability_context, - }; - - // Get capability context - let context = get_global_capability_context()?; - - // Use capability-aware allocation - let mut result = capability_vec(context, CrateId::Runtime, 1)?; - result.push(Value::I32(0)); - Ok(result) - } - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - // For no_std no_alloc, return a fixed array wrapped as Vec-like - use kiln_foundation::{ - bounded::BoundedVec, - budget_aware_provider::CrateId, - safe_managed_alloc, - }; - let provider = safe_managed_alloc!(1024, CrateId::Runtime)?; - let mut result: BoundedVec = BoundedVec::new(provider) - .map_err(|_| Error::runtime_execution_error("Failed to create bounded vector"))?; - result.push(Value::I32(0)).map_err(|_| { - Error::new( - ErrorCategory::Memory, - kiln_error::codes::MEMORY_ALLOCATION_ERROR, - "Failed to push value to result", - ) - })?; - // Convert to Vec for compatibility - this is a temporary workaround - Err(Error::runtime_execution_error("Not implemented for no_std")) - } + use kiln_foundation::{ + budget_aware_provider::CrateId, + capability_allocators::capability_alloc::capability_vec, + memory_init::get_global_capability_context, + }; + + // Get capability context + let context = get_global_capability_context()?; + + // Use capability-aware allocation + let mut result = capability_vec(context, CrateId::Runtime, 1)?; + result.push(Value::I32(0)); + Ok(result) } /// Get current timestamp for performance tracking diff --git a/kiln-runtime/src/platform_stubs.rs b/kiln-runtime/src/platform_stubs.rs index 7829bb55..7cb5a39f 100644 --- a/kiln-runtime/src/platform_stubs.rs +++ b/kiln-runtime/src/platform_stubs.rs @@ -24,10 +24,7 @@ use core::marker::PhantomData; use kiln_error::{Error, ErrorCategory, Result}; // Box for trait objects -#[cfg(feature = "std")] use std::boxed::Box; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::boxed::Box; // Re-export ASIL levels from foundation stubs temporarily use super::foundation_stubs::AsilLevel; @@ -179,33 +176,8 @@ pub use kiln_platform::sync::{AtomicU32, AtomicU64, AtomicUsize, Ordering as Pla pub use self::atomic_fallback::{AtomicU32, AtomicU64, AtomicUsize, Ordering as PlatformOrdering}; // Duration abstraction -#[cfg(feature = "std")] pub use std::time::Duration; -#[cfg(all(not(feature = "std"), feature = "platform-sync"))] -pub use kiln_platform::sync::Duration; - -#[cfg(all(not(feature = "std"), not(feature = "platform-sync")))] -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct Duration { - secs: u64, - nanos: u32, -} - -#[cfg(all(not(feature = "std"), not(feature = "platform-sync")))] -impl Duration { - pub const fn from_millis(millis: u64) -> Self { - Self { - secs: millis / 1000, - nanos: ((millis % 1000) * 1_000_000) as u32, - } - } - - pub const fn as_millis(&self) -> u128 { - self.secs as u128 * 1000 + self.nanos as u128 / 1_000_000 - } -} - /// Platform identification enum with ASIL mapping #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PlatformId { @@ -407,14 +379,13 @@ pub enum PlatformFeature { pub trait PlatformConfig: Send + Sync + 'static {} /// Create platform abstraction based on compile-time features -#[cfg(any(feature = "std", feature = "alloc"))] pub fn create_platform_interface() -> Result> { #[cfg(feature = "platform-sync")] { // Use full platform abstraction from kiln-platform create_full_platform_interface() } - + #[cfg(not(feature = "platform-sync"))] { // Use minimal fallback implementation @@ -422,24 +393,6 @@ pub fn create_platform_interface() -> Result> { } } -/// Create platform interface for pure no_std environments -#[cfg(not(any(feature = "std", feature = "alloc")))] -pub fn create_platform_interface() -> Result<&'static dyn PlatformInterface> { - // In pure no_std, return a static reference - static MINIMAL_PLATFORM: MinimalPlatform = MinimalPlatform { - limits: ComprehensivePlatformLimits { - platform_id: PlatformId::Embedded, - max_total_memory: 256 * 1024, - max_wasm_linear_memory: 64 * 1024, - max_stack_bytes: 16 * 1024, - max_components: 8, - max_debug_overhead: 0, - asil_level: AsilLevel::D, - }, - }; - Ok(&MINIMAL_PLATFORM) -} - /// Minimal platform implementation for no_std without platform features struct MinimalPlatform { limits: ComprehensivePlatformLimits, @@ -479,7 +432,6 @@ fn create_full_platform_interface() -> Result> { } /// Create platform-appropriate limit provider (legacy compatibility) -#[cfg(any(feature = "std", feature = "alloc"))] pub fn create_limit_provider() -> Box { match PlatformId::default() { PlatformId::Linux => Box::new(LinuxLimitProvider), @@ -488,33 +440,11 @@ pub fn create_limit_provider() -> Box { } } -/// Create platform limit provider for pure no_std -#[cfg(not(any(feature = "std", feature = "alloc")))] -pub fn create_limit_provider() -> &'static dyn ComprehensiveLimitProvider { - static DEFAULT_PROVIDER: DefaultLimitProvider = DefaultLimitProvider; - &DEFAULT_PROVIDER -} - /// Platform-agnostic time functions pub fn current_time_ns() -> u64 { - #[cfg(feature = "std")] - { - use std::time::{SystemTime, UNIX_EPOCH}; - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos() as u64) - .unwrap_or(0) - } - - #[cfg(all(not(feature = "std"), feature = "platform-sync"))] - { - kiln_platform::time::current_time_ns() - } - - #[cfg(all(not(feature = "std"), not(feature = "platform-sync")))] - { - // Fallback: use a simple counter for no_std environments - static COUNTER: AtomicU64 = AtomicU64::new(0); - COUNTER.fetch_add(1, core::sync::atomic::Ordering::Relaxed) - } + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0) } \ No newline at end of file diff --git a/kiln-runtime/src/shared_memory.rs b/kiln-runtime/src/shared_memory.rs index 04ead2f3..5b50ae72 100644 --- a/kiln-runtime/src/shared_memory.rs +++ b/kiln-runtime/src/shared_memory.rs @@ -55,7 +55,6 @@ use kiln_instructions::{ use crate::prelude::CoreMemoryType; -#[cfg(any(feature = "std", feature = "alloc"))] use crate::thread_manager::{ ThreadId, ThreadManager, diff --git a/kiln-runtime/src/stackless/engine.rs b/kiln-runtime/src/stackless/engine.rs index 7d9c1a8e..efee0799 100644 --- a/kiln-runtime/src/stackless/engine.rs +++ b/kiln-runtime/src/stackless/engine.rs @@ -23,117 +23,13 @@ use std::{ vec::Vec, }; -// Debug support - only available with std and kiln-debug crate -#[cfg(all(feature = "std", feature = "debugger"))] +// Debug support - only available with kiln-debug crate +#[cfg(feature = "debugger")] use kiln_debug::runtime_traits::{RuntimeDebugger, RuntimeState, DebugAction}; -// For pure no_std without alloc, use bounded collections -#[cfg(not(any(feature = "std", feature = "alloc")))] -use kiln_foundation::{ - bounded::BoundedString, - bounded::BoundedVec, - bounded_collections::BoundedMap, - safe_memory::NoStdProvider, -}; - -// Type aliases for pure no_std mode -#[cfg(not(any(feature = "std", feature = "alloc")))] -type HashMap = BoundedMap>; // 16 concurrent instances max -#[cfg(not(any(feature = "std", feature = "alloc")))] -type Vec = BoundedVec>; // 256 operands max -#[cfg(not(any(feature = "std", feature = "alloc")))] -type String = BoundedString<256>; // 256 byte strings - -// Simple Arc substitute for no_std - just owns the value directly -#[cfg(not(any(feature = "std", feature = "alloc")))] -pub struct Arc(T); - // GC heap reference wrapper types for WebAssembly GC proposal use kiln_foundation::values::{GcStructRef, GcArrayRef}; -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl Arc { - pub fn new(value: T) -> Self { - Arc(value) - } -} - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl core::ops::Deref for Arc { - type Target = T; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl Clone for Arc { - fn clone(&self) -> Self { - Arc(self.0.clone()) - } -} - -// Implement required traits for Arc to work with bounded collections -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl kiln_foundation::traits::Checksummable for Arc -where - T: kiln_foundation::traits::Checksummable, -{ - fn update_checksum(&self, checksum: &mut kiln_foundation::verification::Checksum) { - self.0.update_checksum(checksum); - } -} - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl kiln_foundation::traits::ToBytes for Arc -where - T: kiln_foundation::traits::ToBytes, -{ - fn serialized_size(&self) -> usize { - self.0.serialized_size() - } - - fn to_bytes_with_provider<'a, PStream: kiln_foundation::MemoryProvider>( - &self, - writer: &mut kiln_foundation::traits::WriteStream<'a>, - provider: &PStream, - ) -> kiln_error::Result<()> { - self.0.to_bytes_with_provider(writer, provider) - } -} - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl kiln_foundation::traits::FromBytes for Arc -where - T: kiln_foundation::traits::FromBytes, -{ - fn from_bytes_with_provider<'a, PStream: kiln_foundation::MemoryProvider>( - reader: &mut kiln_foundation::traits::ReadStream<'a>, - provider: &PStream, - ) -> kiln_error::Result { - let value = T::from_bytes_with_provider(reader, provider)?; - Ok(Arc::new(value)) - } -} - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl Default for Arc { - fn default() -> Self { - Arc::new(T::default()) - } -} - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl PartialEq for Arc { - fn eq(&self, other: &Self) -> bool { - self.0 == other.0 - } -} - -#[cfg(not(any(feature = "std", feature = "alloc")))] -impl Eq for Arc {} - use kiln_error::Result; use kiln_foundation::{ traits::BoundedCapacity, @@ -204,7 +100,6 @@ const MAX_CALL_DEPTH: usize = 10000; /// When a Call instruction is encountered, the caller's state is saved here /// and returned to the trampoline. When the callee completes, the trampoline /// pushes results onto operand_stack and resumes execution from pc. -#[cfg(any(feature = "std", feature = "alloc"))] #[derive(Debug)] struct SuspendedFrame { /// Instance ID of the executing instance @@ -235,7 +130,6 @@ pub struct ExecutionStats { /// Outcome of executing a function body. /// Used for trampolining: instead of recursing on the Rust stack, /// execute_function_body returns control flow decisions to the trampoline in execute(). -#[cfg(any(feature = "std", feature = "alloc"))] enum ExecutionOutcome { /// Function completed normally with results Complete(Vec), @@ -285,7 +179,6 @@ pub struct WasiStubMemory { /// This is the "virtual WebAssembly code" approach - the lowered function exists /// in the function index space but executes via our canonical executor. #[derive(Debug, Clone)] -#[cfg(feature = "std")] pub struct LoweredFunction { /// Target interface (e.g., "wasi:io/streams@0.2.4") pub interface: String, @@ -298,7 +191,6 @@ pub struct LoweredFunction { } /// Simple stackless WebAssembly execution engine -#[cfg(any(feature = "std", feature = "alloc"))] pub struct StacklessEngine { /// Currently loaded instances indexed by numeric ID instances: HashMap>, @@ -317,7 +209,6 @@ pub struct StacklessEngine { /// Current instruction pointer instruction_pointer: AtomicU64, /// Host function registry for calling imported functions - #[cfg(feature = "std")] host_registry: Option>, /// Pre-allocated WASI stub memory for each instance wasi_stubs: HashMap, @@ -325,67 +216,38 @@ pub struct StacklessEngine { /// Maps instance_id -> Vec where true means segment was dropped dropped_data_segments: HashMap>, /// Cross-instance import links: (instance_id, import_module, import_name) -> (target_instance_id, export_name) - #[cfg(feature = "std")] import_links: HashMap<(usize, String, String), (usize, String)>, /// Aliased function origins: (instance_id, func_idx) -> original_instance_id /// Tracks which instance an aliased function actually comes from - #[cfg(feature = "std")] aliased_functions: HashMap<(usize, usize), usize>, /// Generic host import handler for all host function calls - #[cfg(feature = "std")] host_handler: Option>, /// Optional runtime debugger for profiling and debugging - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] debugger: Option>, /// Active exception state for exception propagation across calls /// Contains (instance_id, tag_idx, tag_identity, payload) when an exception is in flight /// tag_identity is Some((module, name)) for imported tags, None for local tags - #[cfg(feature = "std")] active_exception: Option<(usize, u32, Option<(String, String)>, Vec)>, /// Storage for caught exceptions (for throw_ref to re-throw) /// Maps exnref index to (tag_idx, payload) - #[cfg(feature = "std")] /// Exception storage: (tag_idx, tag_identity, payload) /// tag_identity is Some((module, name)) for imported tags, None for local tags exception_storage: Vec<(u32, Option<(String, String)>, Vec)>, /// Lowered function registry: (instance_id, func_idx) -> LoweredFunction /// Used for canon.lower synthesized functions that dispatch to canonical executor - #[cfg(feature = "std")] lowered_functions: HashMap<(usize, usize), LoweredFunction>, /// Instance name registry: instance_id -> registered module name /// Used for resolving tag identities in cross-module exception handling - #[cfg(feature = "std")] instance_registry: HashMap, /// Explicit call stack for trampolining (avoids Rust stack recursion) /// Not used directly as a field - the trampoline in execute() uses a local Vec instead. /// Kept for potential future use (e.g., stack inspection). - #[cfg(feature = "std")] call_stack: Vec, } -/// Simple stackless WebAssembly execution engine (no_std version) -#[cfg(not(any(feature = "std", feature = "alloc")))] -pub struct StacklessEngine { - /// Currently loaded instances indexed by numeric ID - instances: HashMap>, - /// Next instance ID - next_instance_id: AtomicU64, - /// Current active instance for execution - current_instance_id: Option, - /// Operand stack for execution (needed by tail_call module) - pub operand_stack: Vec, - /// Call frames count (needed by tail_call module) - pub call_frames_count: usize, - /// Execution statistics (needed by tail_call module) - pub stats: ExecutionStats, - /// Remaining fuel for execution - fuel: AtomicU64, - /// Current instruction pointer - instruction_pointer: AtomicU64, -} - /// Simple RuntimeState implementation for debugger callbacks -#[cfg(all(feature = "std", feature = "debugger"))] +#[cfg(feature = "debugger")] pub struct ExecutionState<'a> { pc: u32, func_idx: u32, @@ -393,7 +255,7 @@ pub struct ExecutionState<'a> { locals: &'a [Value], } -#[cfg(all(feature = "std", feature = "debugger"))] +#[cfg(feature = "debugger")] impl<'a> RuntimeState for ExecutionState<'a> { fn pc(&self) -> u32 { self.pc @@ -522,7 +384,6 @@ fn pop_atomic_address(operand_stack: &mut Vec, memarg_offset: u64) -> kil impl StacklessEngine { /// Create a new stackless engine - #[cfg(any(feature = "std", feature = "alloc"))] pub fn new() -> Self { Self { instances: HashMap::new(), @@ -533,27 +394,18 @@ impl StacklessEngine { stats: ExecutionStats::default(), fuel: AtomicU64::new(u64::MAX), instruction_pointer: AtomicU64::new(0), - #[cfg(feature = "std")] host_registry: None, wasi_stubs: HashMap::new(), dropped_data_segments: HashMap::new(), - #[cfg(feature = "std")] import_links: HashMap::new(), - #[cfg(feature = "std")] aliased_functions: HashMap::new(), - #[cfg(feature = "std")] host_handler: None, - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] debugger: None, - #[cfg(feature = "std")] active_exception: None, - #[cfg(feature = "std")] exception_storage: Vec::new(), - #[cfg(feature = "std")] lowered_functions: HashMap::new(), - #[cfg(feature = "std")] instance_registry: HashMap::new(), - #[cfg(feature = "std")] call_stack: Vec::with_capacity(256), } } @@ -564,25 +416,24 @@ impl StacklessEngine { /// function entry/exit, and traps. This is useful for profiling and debugging. /// /// Note: This has performance overhead - only use when needed. - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] pub fn set_debugger(&mut self, debugger: Box) { self.debugger = Some(debugger); } /// Remove the attached debugger - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] pub fn clear_debugger(&mut self) { self.debugger = None; } /// Check if a debugger is attached - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] pub fn has_debugger(&self) -> bool { self.debugger.is_some() } /// Set the host import handler for resolving host function calls - #[cfg(feature = "std")] pub fn set_host_handler(&mut self, handler: Box) { self.host_handler = Some(handler); } @@ -592,7 +443,6 @@ impl StacklessEngine { /// When a module calls a function at this (instance_id, func_idx), the engine /// will dispatch to the canonical executor instead of executing bytecode. /// This is the Component Model's "synthesized core function" mechanism. - #[cfg(feature = "std")] pub fn register_lowered_function( &mut self, instance_id: usize, @@ -624,13 +474,11 @@ impl StacklessEngine { /// This associates a human-readable module name with an instance ID. /// Used for resolving tag identities in catch handlers when exceptions /// propagate across module boundaries. - #[cfg(feature = "std")] pub fn register_instance_name(&mut self, instance_id: usize, name: &str) { self.instance_registry.insert(instance_id, name.to_string()); } /// Get the registered name for an instance - #[cfg(feature = "std")] pub fn get_instance_registered_name(&self, instance_id: usize) -> Option<&String> { self.instance_registry.get(&instance_id) } @@ -641,7 +489,6 @@ impl StacklessEngine { /// - For imported tags: returns the import source (module_name, field_name) /// - For exported local tags (with registered instance): returns (registered_name, export_name) /// - For non-exported local tags: returns None (only matches within same module) - #[cfg(feature = "std")] fn get_effective_tag_identity( &self, instance_id: usize, @@ -665,7 +512,6 @@ impl StacklessEngine { } /// Check if a function is a lowered function (from canon.lower) - #[cfg(feature = "std")] fn is_lowered_function(&self, instance_id: usize, func_idx: usize) -> bool { self.lowered_functions.contains_key(&(instance_id, func_idx)) } @@ -675,7 +521,7 @@ impl StacklessEngine { /// Called when an import link target has a `__canon_lower_` prefix export name. /// This handles the canonical ABI lifting and WASI dispatch without needing /// the lowered_functions map (which may have incorrect indices for mixed exports). - #[cfg(all(feature = "std", feature = "wasi"))] + #[cfg(feature = "wasi")] fn dispatch_canon_lowered( &mut self, instance_id: usize, @@ -717,7 +563,7 @@ impl StacklessEngine { /// /// Looks up the lowered function metadata and delegates to `dispatch_canon_lowered` /// which routes through the HostImportHandler trait. - #[cfg(all(feature = "std", feature = "wasi"))] + #[cfg(feature = "wasi")] fn execute_lowered_function( &mut self, instance_id: usize, @@ -732,7 +578,6 @@ impl StacklessEngine { } /// Register a cross-instance import link - #[cfg(feature = "std")] pub fn register_import_link( &mut self, instance_id: usize, @@ -746,7 +591,6 @@ impl StacklessEngine { } /// Call an exported function in another instance by name - #[cfg(feature = "std")] fn call_exported_function( &mut self, target_instance_id: usize, @@ -821,7 +665,6 @@ impl StacklessEngine { /// Resolve an exported function to (instance_id, func_idx) without executing it. /// Used by the trampoline to redirect import calls without recursion. - #[cfg(feature = "std")] fn resolve_export_func_idx( &self, target_instance_id: usize, @@ -857,7 +700,6 @@ impl StacklessEngine { /// the frame will execute the handler code. /// /// Returns true if a handler was found and applied, false otherwise. - #[cfg(feature = "std")] fn find_and_apply_exception_handler(&mut self, frame: &mut SuspendedFrame) -> bool { use kiln_foundation::types::Instruction; @@ -1043,13 +885,11 @@ impl StacklessEngine { } /// Set the host function registry for imported function calls - #[cfg(feature = "std")] pub fn set_host_registry(&mut self, registry: Arc) { self.host_registry = Some(registry); } /// Add an import link for cross-instance calls - #[cfg(feature = "std")] pub fn add_import_link( &mut self, instance_id: usize, @@ -1067,7 +907,6 @@ impl StacklessEngine { /// Remap import links from old_id to new_id /// This is needed when link_import is called with module_id before instantiation, /// but runtime lookup uses instance_id (which is assigned during instantiation) - #[cfg(feature = "std")] pub fn remap_import_links(&mut self, old_id: usize, new_id: usize) { if old_id == new_id { return; @@ -1103,7 +942,6 @@ impl StacklessEngine { /// Register an aliased function origin /// This tracks which instance a function actually belongs to when it's aliased - #[cfg(feature = "std")] pub fn register_aliased_function( &mut self, instance_id: usize, @@ -1197,49 +1035,6 @@ impl StacklessEngine { Ok((result, bytes_read)) } - /// Create a new stackless engine (no_std version) - #[cfg(not(any(feature = "std", feature = "alloc")))] - pub fn new() -> kiln_error::Result { - use kiln_foundation::{ - budget_aware_provider::CrateId, - safe_managed_alloc, - }; - - let provider = safe_managed_alloc!(4096, CrateId::Runtime)?; - let instances = BoundedMap::new(provider.clone()) - .map_err(|_| kiln_error::Error::runtime_error("Failed to create instances map"))?; - let operand_stack = BoundedVec::new(provider) - .map_err(|_| kiln_error::Error::runtime_error("Failed to create operand stack"))?; - - #[cfg(any(feature = "std", feature = "alloc"))] - { - Ok(Self { - instances: HashMap::new(), - next_instance_id: AtomicU64::new(1), - current_instance_id: None, - operand_stack: Vec::new(), - call_frames_count: 0, - stats: ExecutionStats::default(), - fuel: AtomicU64::new(u64::MAX), - instruction_pointer: AtomicU64::new(0), - }) - } - - #[cfg(not(any(feature = "std", feature = "alloc")))] - { - Ok(Self { - instances, - next_instance_id: AtomicU64::new(1), - current_instance_id: None, - operand_stack, - call_frames_count: 0, - stats: ExecutionStats::default(), - fuel: AtomicU64::new(u64::MAX), - instruction_pointer: AtomicU64::new(0), - }) - } - } - /// Returns the instance ID that will be assigned to the next module /// registered via `set_current_module`. This allows callers to create /// a `ModuleInstance` with the correct engine-assigned ID *before* @@ -1305,7 +1100,6 @@ impl StacklessEngine { /// Get an instance by ID /// /// Returns a reference to the ModuleInstance if found. - #[cfg(any(feature = "std", feature = "alloc"))] pub fn get_instance(&self, instance_id: usize) -> Option> { self.instances.get(&instance_id).cloned() } @@ -1319,7 +1113,6 @@ impl StacklessEngine { /// /// # Returns /// The function results - #[cfg(any(feature = "std", feature = "alloc"))] pub fn execute( &mut self, instance_id: usize, @@ -1401,7 +1194,6 @@ impl StacklessEngine { Err(e) => { eprintln!("[DEBUG-TRAMPOLINE-ERR] error={}, has_active_exception={}, pending_frames={}", e, self.active_exception.is_some(), pending_frames.len()); // Handle exception unwinding through pending frames - #[cfg(feature = "std")] if self.active_exception.is_some() { // Current function (which errored) is done self.call_frames_count = self.call_frames_count.saturating_sub(1); @@ -1445,7 +1237,6 @@ impl StacklessEngine { /// /// # Panics /// Panics if the function attempts a Call or TailCall (violating leaf contract). - #[cfg(any(feature = "std", feature = "alloc"))] fn execute_leaf_function( &mut self, instance_id: usize, @@ -1482,7 +1273,6 @@ impl StacklessEngine { } /// Internal function body execution - can return TailCall for trampolining - #[cfg(any(feature = "std", feature = "alloc"))] fn execute_function_body( &mut self, instance_id: usize, @@ -1496,7 +1286,6 @@ impl StacklessEngine { // Clone the instance to avoid holding a borrow on self.instances // This allows us to call &mut self methods (like execute, call_wasi_function) // during execution without borrow checker conflicts. - #[cfg(any(feature = "std", feature = "alloc"))] let instance = { let found = self.instances.get(&instance_id); if found.is_none() { @@ -1507,13 +1296,6 @@ impl StacklessEngine { found.unwrap().clone() }; - #[cfg(not(any(feature = "std", feature = "alloc")))] - let instance = self - .instances - .get(&instance_id)? - .ok_or_else(|| kiln_error::Error::runtime_execution_error("Instance not found"))? - .clone(); - // Check if this function is aliased and get the correct module // Clone the Arc so we own it and don't hold a borrow let module: Arc = { @@ -1569,7 +1351,7 @@ impl StacklessEngine { if let Some((target_instance_id, export_name)) = linked { // Check if this is a canon-lowered function - #[cfg(all(feature = "std", feature = "wasi"))] + #[cfg(feature = "wasi")] if export_name.starts_with("__canon_lower_") { let canon_suffix = &export_name["__canon_lower_".len()..]; if let Some(sep_pos) = canon_suffix.rfind("::") { @@ -1686,7 +1468,7 @@ impl StacklessEngine { // Take debugger out of self to use during execution (avoids borrow issues) // This is done for both fresh calls and resumes - the debugger is restored // before returning Call outcomes and re-taken on resume. - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] let mut debugger_opt = self.debugger.take(); // Save the current function index for SuspendedFrame construction. @@ -1821,7 +1603,7 @@ impl StacklessEngine { trace!("pc={}, instruction={:?}", pc, instruction); // Debugger callback - notify debugger of instruction execution - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] if let Some(ref mut debugger) = debugger_opt { let state = ExecutionState { pc: pc as u32, @@ -1841,7 +1623,7 @@ impl StacklessEngine { // The trap should propagate as an error, not be silently ignored. // This can occur in panic paths when the panic hook is NULL, // or after proc_exit is called. - #[cfg(all(feature = "std", feature = "tracing"))] + #[cfg(feature = "tracing")] { // Print some context about what led to unreachable let prev_str = if pc > 0 { format!("{:?}", instructions.get(pc - 1)) } else { "N/A".to_string() }; @@ -1987,7 +1769,7 @@ impl StacklessEngine { // dispatch to the canonical executor instead of using import_links. // This prevents infinite recursion when adapter modules import canon-lowered // functions that are backed by InlineExports with no real module. - #[cfg(all(feature = "std", feature = "wasi"))] + #[cfg(feature = "wasi")] { let is_lowered = self.is_lowered_function(instance_id, func_idx as usize); if is_lowered { @@ -2013,7 +1795,7 @@ impl StacklessEngine { pc += 1; continue; } - } // end #[cfg(all(feature = "std", feature = "wasi"))] + } // end #[cfg(feature = "wasi")] // Find the import by index let import_result = self.find_import_by_index(&module, func_idx as usize); @@ -2031,7 +1813,6 @@ impl StacklessEngine { // Check if this import is linked to another instance // NOTE: Component adapter modules handle P2→P1 translation. // ALL imports (including WASI) should use cross-instance linking when linked. - #[cfg(feature = "std")] { // Clone the values to avoid holding a borrow during call_exported_function let import_key = (instance_id, module_name.clone(), field_name.clone()); @@ -2050,7 +1831,7 @@ impl StacklessEngine { // starts with __canon_lower_). These are WASI functions // that should be dispatched via the canonical ABI executor, // not as cross-instance calls. - #[cfg(all(feature = "std", feature = "wasi"))] + #[cfg(feature = "wasi")] if export_name.starts_with("__canon_lower_") { // Parse interface::function from __canon_lower_{interface}::{function} let canon_suffix = &export_name["__canon_lower_".len()..]; @@ -2196,7 +1977,7 @@ impl StacklessEngine { stack_len = operand_stack.len(), "[CALL] Parameter and stack info" ); - #[cfg(all(feature = "std", feature = "tracing"))] + #[cfg(feature = "tracing")] if func_idx == 94 || func_idx == 223 || func_idx == 232 || func_idx == 233 { trace!( func_idx = func_idx, @@ -2205,7 +1986,7 @@ impl StacklessEngine { ); } // Trace func 235 (free) to see what pointer is being freed - #[cfg(all(feature = "std", feature = "tracing"))] + #[cfg(feature = "tracing")] if func_idx == 235 || func_idx == 236 { trace!( func_idx = func_idx, @@ -2214,7 +1995,7 @@ impl StacklessEngine { ); } // Trace func 244 (format string loop) to see arguments - #[cfg(all(feature = "std", feature = "tracing"))] + #[cfg(feature = "tracing")] if func_idx == 244 { trace!( args = ?operand_stack.iter().rev().take(8).collect::>(), @@ -2249,7 +2030,7 @@ impl StacklessEngine { // push results onto our operand_stack and resume us at pc+1. // Exception handling is managed by the trampoline via // find_and_apply_exception_handler on pending frames. - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] { self.debugger = debugger_opt; } @@ -2432,7 +2213,7 @@ impl StacklessEngine { } // Check if this is a lowered function in the target instance - #[cfg(all(feature = "std", feature = "wasi"))] + #[cfg(feature = "wasi")] if self.is_lowered_function(target_id, func_idx) { let param_count = actual_type.params.len(); let mut call_args = Vec::new(); @@ -2490,7 +2271,7 @@ impl StacklessEngine { // CHECK FOR LOWERED FUNCTION: If this function was created by canon.lower, // dispatch to the canonical executor instead of executing bytecode. // This prevents infinite recursion when shim modules have self-referential tables. - #[cfg(all(feature = "std", feature = "wasi"))] + #[cfg(feature = "wasi")] if self.is_lowered_function(instance_id, func_idx) { #[cfg(feature = "tracing")] trace!( @@ -2531,7 +2312,7 @@ impl StacklessEngine { // Track call_indirect to func 138 (iterator next) static CALL_138_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - #[cfg(all(feature = "std", feature = "tracing"))] + #[cfg(feature = "tracing")] if func_idx == 138 { let call_num = CALL_138_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); trace!( @@ -2605,7 +2386,6 @@ impl StacklessEngine { ); // Check if this import is linked to another instance - #[cfg(feature = "std")] { let import_key = (instance_id, module_name.clone(), field_name.clone()); let linked = self.import_links.get(&import_key) @@ -2807,7 +2587,7 @@ impl StacklessEngine { call_args.reverse(); // Restore debugger before returning for tail call - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] { self.debugger = debugger_opt; } @@ -2844,7 +2624,7 @@ impl StacklessEngine { call_args.reverse(); // Restore debugger before returning for tail call - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] { self.debugger = debugger_opt; } @@ -2933,7 +2713,7 @@ impl StacklessEngine { call_args.reverse(); // Restore debugger before returning for tail call - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] { self.debugger = debugger_opt; } @@ -4496,7 +4276,7 @@ impl StacklessEngine { let value = i64::from_le_bytes(buffer); #[cfg(feature = "tracing")] trace!("I64Load: read value {} from address {}", value, eff_addr); - #[cfg(all(feature = "std", feature = "tracing"))] + #[cfg(feature = "tracing")] { trace!( value = value, @@ -5916,7 +5696,6 @@ impl StacklessEngine { ); // Per WebAssembly spec: bounds check MUST happen before checking size==0 - #[cfg(any(feature = "std", feature = "alloc"))] { let dst_memory_wrapper = instance.memory(dst_mem_idx)?; let dst_memory = &dst_memory_wrapper.0; @@ -5975,8 +5754,6 @@ impl StacklessEngine { } } } - #[cfg(not(any(feature = "std", feature = "alloc")))] - return Err(kiln_error::Error::runtime_error("MemoryCopy requires std or alloc feature")); } } Instruction::MemoryFill(mem_idx) => { @@ -6114,7 +5891,6 @@ impl StacklessEngine { return Err(kiln_error::Error::runtime_trap("out of bounds memory access")); } - #[cfg(any(feature = "std", feature = "alloc"))] { let src_slice = &data_segment.init[s as usize..src_end as usize]; if let Err(e) = memory.write_shared(d as u32, src_slice) { @@ -9827,7 +9603,6 @@ impl StacklessEngine { } } else { // No handler found in current function - store exception state for propagation - #[cfg(feature = "std")] { // Get effective tag identity for cross-module exception matching // This handles both imported tags and exported local tags @@ -10010,7 +9785,6 @@ impl StacklessEngine { } } else { // No handler - propagate to caller - #[cfg(feature = "std")] { // Use the stored tag identity for cross-module exception matching // (thrown_tag_identity was retrieved from exception_storage) @@ -10986,7 +10760,7 @@ impl StacklessEngine { trace!("Returning {} results", results.len()); // Restore debugger back to self - #[cfg(all(feature = "std", feature = "debugger"))] + #[cfg(feature = "debugger")] { self.debugger = debugger_opt; } @@ -11255,7 +11029,6 @@ impl StacklessEngine { } /// Find an import's parameter count by module and field name - #[cfg(feature = "std")] fn get_import_param_count_by_name( module: &crate::module::Module, module_name: &str, @@ -11288,7 +11061,6 @@ impl StacklessEngine { } /// Collect import arguments from stack by module/field name - #[cfg(feature = "std")] fn collect_import_args_by_name( module: &crate::module::Module, module_name: &str, @@ -11309,7 +11081,6 @@ impl StacklessEngine { } /// Call cabi_realloc to allocate memory in WASM instance - #[cfg(any(feature = "std", feature = "alloc"))] fn call_cabi_realloc(&mut self, instance_id: usize, func_idx: usize, old_ptr: u32, old_size: u32, align: u32, new_size: u32) -> Result { #[cfg(feature = "tracing")] @@ -11474,7 +11245,6 @@ impl StacklessEngine { ); // Set on host_handler (the dispatch target for get-arguments calls) - #[cfg(feature = "std")] if let Some(ref mut handler) = self.host_handler { handler.set_args_allocation(list_ptr, string_ptrs); } @@ -11599,7 +11369,6 @@ impl StacklessEngine { module: &crate::module::Module, instance_id: usize, ) -> Result> { - #[cfg(feature = "std")] use std::io::Write; #[cfg(feature = "tracing")] @@ -11611,7 +11380,6 @@ impl StacklessEngine { // properly handle the stack arguments. // // The host_registry is kept for non-WASI host functions that don't need stack args. - #[cfg(feature = "std")] if let Some(ref registry) = self.host_registry { // Only use host_registry for non-WASI functions // WASI functions need proper stack argument marshalling done below @@ -11646,7 +11414,6 @@ impl StacklessEngine { // Use host_handler for WASI dispatch (when configured) // This is the proper architecture - host_handler routes to WasiDispatcher - #[cfg(feature = "std")] { // ON-DEMAND ALLOCATION for get-arguments // This MUST happen AFTER _start has initialized the component's allocator. @@ -12580,15 +12347,9 @@ fn execute_simd_mem_lane_op( } impl Default for StacklessEngine { - #[cfg(any(feature = "std", feature = "alloc"))] fn default() -> Self { Self::new() } - - #[cfg(not(any(feature = "std", feature = "alloc")))] - fn default() -> Self { - Self::new().expect("Failed to create default StacklessEngine in no_std mode") - } } // Additional types that might be needed - using simple type aliases to avoid diff --git a/kiln-runtime/src/stackless/mod.rs b/kiln-runtime/src/stackless/mod.rs index 3783b11b..07256f5f 100644 --- a/kiln-runtime/src/stackless/mod.rs +++ b/kiln-runtime/src/stackless/mod.rs @@ -7,20 +7,13 @@ //! The stackless engine uses a state machine approach to track execution state //! and allows for pausing and resuming execution at any point. -#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::String; -#[cfg(feature = "std")] -use alloc::string::String; -#[cfg(not(any(feature = "std", feature = "alloc")))] -type String = - kiln_foundation::bounded::BoundedString<256>; pub mod engine; pub mod extensions; pub mod frame; pub mod simd_ops; -#[cfg(feature = "std")] pub mod tail_call; pub use engine::{ diff --git a/kiln-runtime/src/stackless/tail_call.rs b/kiln-runtime/src/stackless/tail_call.rs index 585e6f7f..9be43308 100644 --- a/kiln-runtime/src/stackless/tail_call.rs +++ b/kiln-runtime/src/stackless/tail_call.rs @@ -4,8 +4,6 @@ //! make tail calls without growing the call stack. This is essential for //! functional programming patterns and recursive algorithms. -// alloc is imported in lib.rs with proper feature gates - use kiln_error::{ Error, Result, @@ -17,6 +15,8 @@ use kiln_foundation::{ use kiln_instructions::control_ops::ControlContext; // Type alias for FuncType to match module_instance.rs +use alloc::vec::Vec; + use crate::bounded_runtime_infra::RuntimeProvider; use crate::{ module_instance::ModuleInstance, @@ -28,9 +28,6 @@ use crate::{ }; type KilnFuncType = kiln_foundation::types::FuncType; -#[cfg(feature = "std")] -use alloc::vec::Vec; - /// Tail call implementation for the stackless engine impl StacklessEngine { /// Execute a tail call to a function diff --git a/kiln-runtime/src/state/mod.rs b/kiln-runtime/src/state/mod.rs index bc8f84d1..9c3e1d01 100644 --- a/kiln-runtime/src/state/mod.rs +++ b/kiln-runtime/src/state/mod.rs @@ -5,8 +5,7 @@ pub mod serialization; -// Re-export functions conditionally -#[cfg(any(feature = "std", feature = "alloc"))] +// Re-export functions pub use serialization::{ create_state_section, extract_state_section, diff --git a/kiln-runtime/src/state/serialization.rs b/kiln-runtime/src/state/serialization.rs index beeeae2d..639a8951 100644 --- a/kiln-runtime/src/state/serialization.rs +++ b/kiln-runtime/src/state/serialization.rs @@ -3,13 +3,6 @@ //! This module provides utilities for serializing and deserializing WebAssembly //! runtime state using custom sections. -// alloc is imported in lib.rs with proper feature gates -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::{ - string::String, - vec::Vec, -}; -#[cfg(feature = "std")] use alloc::{ string::String, vec::Vec, @@ -32,16 +25,6 @@ use kiln_format::{ STATE_VERSION, }, }; -#[cfg(not(any(feature = "std")))] -use kiln_format::{ - WasmString, - WasmVec, -}; -#[cfg(not(any(feature = "std")))] -use kiln_foundation::{ - MemoryProvider, - NoStdProvider, -}; /// Constants for state section names pub const STATE_SECTION_PREFIX: &str = "kiln-state"; @@ -63,7 +46,6 @@ pub enum StateSection { impl StateSection { /// Get the section name for this state section type - #[cfg(feature = "std")] pub fn name(&self) -> String { match self { Self::Meta => format!("{}-meta", STATE_SECTION_PREFIX), @@ -74,18 +56,6 @@ impl StateSection { } } - /// Get the section name for this state section type (no_std version) - #[cfg(not(any(feature = "std")))] - pub fn name(&self) -> &'static str { - match self { - Self::Meta => "kiln-state-meta", - Self::Stack => "kiln-state-stack", - Self::Frames => "kiln-state-frames", - Self::Globals => "kiln-state-globals", - Self::Memory => "kiln-state-memory", - } - } - /// Convert a section name to a StateSection pub fn from_name(name: &str) -> Option { match name { @@ -125,7 +95,6 @@ pub struct StateHeader { } /// Create a custom section containing serialized state -#[cfg(feature = "std")] pub fn create_state_section( section_type: StateSection, data: &[u8], @@ -170,7 +139,6 @@ pub fn create_state_section( } /// Extract state data from a custom section -#[cfg(feature = "std")] pub fn extract_state_section(section: &CustomSection) -> Result<(StateHeader, Vec)> { // Verify that this is a valid state section let section_type = StateSection::from_name(§ion.name) @@ -265,14 +233,7 @@ pub fn extract_state_section(section: &CustomSection) -> Result<(StateHeader, Ve /// `true` if the module contains at least one state section pub fn has_state_sections(custom_sections: &[CustomSection]) -> bool { custom_sections.iter().any(|section| { - #[cfg(feature = "std")] - { - section.name.starts_with(STATE_SECTION_PREFIX) - } - #[cfg(not(any(feature = "std")))] - { - section.name.starts_with(STATE_SECTION_PREFIX) - } + section.name.starts_with(STATE_SECTION_PREFIX) }) } diff --git a/kiln-runtime/src/tests/integration_tests.rs b/kiln-runtime/src/tests/integration_tests.rs index f0f373b5..44a18ade 100644 --- a/kiln-runtime/src/tests/integration_tests.rs +++ b/kiln-runtime/src/tests/integration_tests.rs @@ -1,5 +1,4 @@ #[cfg(test)] -#[cfg(feature = "std")] mod tests { use kiln_error::Result; use kiln_foundation::{ diff --git a/kiln-runtime/src/type_conversion/locals_conversion.rs b/kiln-runtime/src/type_conversion/locals_conversion.rs index 0f1611e7..075ec175 100644 --- a/kiln-runtime/src/type_conversion/locals_conversion.rs +++ b/kiln-runtime/src/type_conversion/locals_conversion.rs @@ -3,8 +3,6 @@ //! This module provides conversion between different representations of local //! variables used in the Kiln execution pipeline. -// alloc is imported in lib.rs with proper feature gates -#[cfg(any(feature = "std", feature = "alloc"))] use alloc::vec::Vec; use kiln_error::Result; @@ -82,7 +80,6 @@ pub fn convert_locals_to_bounded( /// Convert a BoundedVec back to a flat Vec /// This is useful for compatibility with APIs that expect the flat /// representation -#[cfg(any(feature = "std", feature = "alloc"))] pub fn expand_locals_to_flat( bounded_locals: &BoundedVec, ) -> Result> { diff --git a/kiln-runtime/src/type_conversion/mod.rs b/kiln-runtime/src/type_conversion/mod.rs index 92a9c1b5..361a494f 100644 --- a/kiln-runtime/src/type_conversion/mod.rs +++ b/kiln-runtime/src/type_conversion/mod.rs @@ -6,9 +6,7 @@ pub mod locals_conversion; pub mod slice_adapter; -pub use locals_conversion::{convert_locals_to_bounded, convert_locals_to_bounded_with_provider}; -#[cfg(any(feature = "std", feature = "alloc"))] -pub use locals_conversion::expand_locals_to_flat; +pub use locals_conversion::{convert_locals_to_bounded, convert_locals_to_bounded_with_provider, expand_locals_to_flat}; pub use slice_adapter::{ adapt_slice_to_bounded, SliceAdapter, diff --git a/kiln-runtime/src/wasip2_host.rs b/kiln-runtime/src/wasip2_host.rs index 4420c3ad..f2c443f0 100644 --- a/kiln-runtime/src/wasip2_host.rs +++ b/kiln-runtime/src/wasip2_host.rs @@ -74,7 +74,6 @@ pub struct ResourceHandle(pub u32); /// Callback type for cabi_realloc invocation /// /// Parameters: (old_ptr, old_size, align, new_size) -> Result -#[cfg(feature = "std")] pub type ReallocCallback<'a> = &'a mut dyn FnMut(i32, i32, i32, i32) -> Result; /// Context for lowering ComponentValues to core WASM values @@ -85,7 +84,6 @@ pub struct LoweringContext<'a> { /// Mutable reference to linear memory pub memory: &'a mut [u8], /// Callback to invoke cabi_realloc for memory allocation - #[cfg(feature = "std")] pub realloc: Option>, /// Current allocation offset (for no_std fallback) pub alloc_offset: u32, @@ -1259,22 +1257,16 @@ impl Wasip2Host { // Write to the appropriate target match &self.output_streams[stream_idx].target { OutputTarget::Stdout => { - #[cfg(feature = "std")] - { - use std::io::{self, Write}; - #[cfg(feature = "tracing")] - kiln_foundation::tracing::trace!(bytes = trimmed_data.len(), "Writing to STDOUT"); - let _ = io::stdout().write_all(trimmed_data); - let _ = io::stdout().flush(); - } + use std::io::{self, Write}; + #[cfg(feature = "tracing")] + kiln_foundation::tracing::trace!(bytes = trimmed_data.len(), "Writing to STDOUT"); + let _ = io::stdout().write_all(trimmed_data); + let _ = io::stdout().flush(); }, OutputTarget::Stderr => { - #[cfg(feature = "std")] - { - use std::io::{self, Write}; - let _ = io::stderr().write_all(trimmed_data); - let _ = io::stderr().flush(); - } + use std::io::{self, Write}; + let _ = io::stderr().write_all(trimmed_data); + let _ = io::stderr().flush(); }, OutputTarget::File(_path) => { // File output not yet implemented @@ -1453,7 +1445,6 @@ impl Wasip2Host { Ok(vec![Value::I32((handle + 1000) as i32)]) }, _ => { - #[cfg(feature = "std")] eprintln!("[WASIP2] Unknown function: {}/{}", base_interface, function); Err(kiln_error::Error::runtime_error("Unknown wasip2 function")) } @@ -1605,25 +1596,19 @@ impl Wasip2Host { match &self.output_streams[stream_idx].target { OutputTarget::Stdout => { - #[cfg(feature = "std")] - { - use std::io::{self, Write}; - io::stdout().write_all(data).map_err(|_| - kiln_error::Error::runtime_error("stdout write failed"))?; - io::stdout().flush().map_err(|_| - kiln_error::Error::runtime_error("stdout flush failed"))?; - } + use std::io::{self, Write}; + io::stdout().write_all(data).map_err(|_| + kiln_error::Error::runtime_error("stdout write failed"))?; + io::stdout().flush().map_err(|_| + kiln_error::Error::runtime_error("stdout flush failed"))?; Ok(()) }, OutputTarget::Stderr => { - #[cfg(feature = "std")] - { - use std::io::{self, Write}; - io::stderr().write_all(data).map_err(|_| - kiln_error::Error::runtime_error("stderr write failed"))?; - io::stderr().flush().map_err(|_| - kiln_error::Error::runtime_error("stderr flush failed"))?; - } + use std::io::{self, Write}; + io::stderr().write_all(data).map_err(|_| + kiln_error::Error::runtime_error("stderr write failed"))?; + io::stderr().flush().map_err(|_| + kiln_error::Error::runtime_error("stderr flush failed"))?; Ok(()) }, OutputTarget::File(_) => {