1use crate::{
22 host::HostState,
23 instance_wrapper::{EntryPoint, InstanceWrapper, MemoryWrapper},
24 util::{self, replace_strategy_if_broken},
25};
26
27use parking_lot::Mutex;
28use sc_allocator::{AllocationStats, FreeingBumpHeapAllocator};
29use sc_executor_common::{
30 error::{Error, Result, WasmError},
31 runtime_blob::RuntimeBlob,
32 util::checked_range,
33 wasm_runtime::{HeapAllocStrategy, WasmInstance, WasmModule},
34};
35use sp_runtime_interface::unpack_ptr_and_len;
36use sp_wasm_interface::{HostFunctions, Pointer, WordSize};
37use std::{
38 path::{Path, PathBuf},
39 sync::{
40 atomic::{AtomicBool, Ordering},
41 Arc,
42 },
43};
44use wasmtime::{AsContext, Cache, CacheConfig, Engine, Memory};
45
46const MAX_INSTANCE_COUNT: u32 = 64;
47
48#[derive(Default)]
49pub(crate) struct StoreData {
50 pub(crate) host_state: Option<HostState>,
52 pub(crate) memory: Option<Memory>,
54}
55
56impl StoreData {
57 pub fn host_state_mut(&mut self) -> Option<&mut HostState> {
59 self.host_state.as_mut()
60 }
61
62 pub fn memory(&self) -> Memory {
64 self.memory.expect("memory is always set; qed")
65 }
66}
67
68pub(crate) type Store = wasmtime::Store<StoreData>;
69
70enum Strategy {
71 RecreateInstance(InstanceCreator),
72}
73
74struct InstanceCreator {
75 engine: Engine,
76 instance_pre: Arc<wasmtime::InstancePre<StoreData>>,
77 instance_counter: Arc<InstanceCounter>,
78}
79
80impl InstanceCreator {
81 fn instantiate(&mut self) -> Result<InstanceWrapper> {
82 InstanceWrapper::new(&self.engine, &self.instance_pre, self.instance_counter.clone())
83 }
84}
85
86pub(crate) struct ReleaseInstanceHandle {
88 counter: Arc<InstanceCounter>,
89}
90
91impl Drop for ReleaseInstanceHandle {
92 fn drop(&mut self) {
93 {
94 let mut counter = self.counter.counter.lock();
95 *counter = counter.saturating_sub(1);
96 }
97
98 self.counter.wait_for_instance.notify_one();
99 }
100}
101
102#[derive(Default)]
109pub(crate) struct InstanceCounter {
110 counter: Mutex<u32>,
111 wait_for_instance: parking_lot::Condvar,
112}
113
114impl InstanceCounter {
115 pub fn acquire_instance(self: Arc<Self>) -> ReleaseInstanceHandle {
122 let mut counter = self.counter.lock();
123
124 while *counter >= MAX_INSTANCE_COUNT {
125 self.wait_for_instance.wait(&mut counter);
126 }
127 *counter += 1;
128
129 ReleaseInstanceHandle { counter: self.clone() }
130 }
131}
132
133pub struct WasmtimeRuntime {
136 engine: Engine,
137 instance_pre: Arc<wasmtime::InstancePre<StoreData>>,
138 instantiation_strategy: InternalInstantiationStrategy,
139 instance_counter: Arc<InstanceCounter>,
140}
141
142impl WasmModule for WasmtimeRuntime {
143 fn new_instance(&self) -> Result<Box<dyn WasmInstance>> {
144 let strategy = match self.instantiation_strategy {
145 InternalInstantiationStrategy::Builtin => Strategy::RecreateInstance(InstanceCreator {
146 engine: self.engine.clone(),
147 instance_pre: self.instance_pre.clone(),
148 instance_counter: self.instance_counter.clone(),
149 }),
150 };
151
152 Ok(Box::new(WasmtimeInstance { strategy }))
153 }
154}
155
156pub struct WasmtimeInstance {
159 strategy: Strategy,
160}
161
162impl WasmtimeInstance {
163 fn call_impl(
164 &mut self,
165 method: &str,
166 data: &[u8],
167 allocation_stats: &mut Option<AllocationStats>,
168 ) -> Result<Vec<u8>> {
169 match &mut self.strategy {
170 Strategy::RecreateInstance(ref mut instance_creator) => {
171 let mut instance_wrapper = instance_creator.instantiate()?;
172 let heap_base = instance_wrapper.extract_heap_base()?;
173 let entrypoint = instance_wrapper.resolve_entrypoint(method)?;
174 let allocator = FreeingBumpHeapAllocator::new(heap_base);
175
176 perform_call(data, &mut instance_wrapper, entrypoint, allocator, allocation_stats)
177 },
178 }
179 }
180}
181
182impl WasmInstance for WasmtimeInstance {
183 fn call_with_allocation_stats(
184 &mut self,
185 method: &str,
186 data: &[u8],
187 ) -> (Result<Vec<u8>>, Option<AllocationStats>) {
188 let mut allocation_stats = None;
189 let result = self.call_impl(method, data, &mut allocation_stats);
190 (result, allocation_stats)
191 }
192}
193
194fn setup_wasmtime_caching(
198 cache_path: &Path,
199 config: &mut wasmtime::Config,
200) -> std::result::Result<(), String> {
201 use std::fs;
202
203 let wasmtime_cache_root = cache_path.join("wasmtime");
204 fs::create_dir_all(&wasmtime_cache_root)
205 .map_err(|err| format!("cannot create the dirs to cache: {}", err))?;
206
207 let mut cache_config = CacheConfig::new();
208 cache_config.with_directory(cache_path);
209
210 let cache =
211 Cache::new(cache_config).map_err(|err| format!("failed to initiate Cache: {err:?}"))?;
212
213 config.cache(Some(cache));
214
215 Ok(())
216}
217
218fn common_config(semantics: &Semantics) -> std::result::Result<wasmtime::Config, WasmError> {
219 let mut config = wasmtime::Config::new();
220 config.cranelift_opt_level(wasmtime::OptLevel::SpeedAndSize);
221 config.cranelift_nan_canonicalization(semantics.canonicalize_nans);
222
223 let profiler = match std::env::var_os("WASMTIME_PROFILING_STRATEGY") {
224 Some(os_string) if os_string == "jitdump" => wasmtime::ProfilingStrategy::JitDump,
225 Some(os_string) if os_string == "perfmap" => wasmtime::ProfilingStrategy::PerfMap,
226 None => wasmtime::ProfilingStrategy::None,
227 Some(_) => {
228 static UNKNOWN_PROFILING_STRATEGY: AtomicBool = AtomicBool::new(false);
230 if !UNKNOWN_PROFILING_STRATEGY.swap(true, Ordering::Relaxed) {
232 log::warn!("WASMTIME_PROFILING_STRATEGY is set to unknown value, ignored.");
233 }
234 wasmtime::ProfilingStrategy::None
235 },
236 };
237 config.profiler(profiler);
238
239 let native_stack_max = match semantics.deterministic_stack_limit {
240 Some(DeterministicStackLimit { native_stack_max, .. }) => native_stack_max,
241
242 None => 1024 * 1024,
247 };
248
249 config.max_wasm_stack(native_stack_max as usize);
250
251 config.parallel_compilation(semantics.parallel_compilation);
252
253 config.wasm_reference_types(semantics.wasm_reference_types);
256 config.wasm_simd(semantics.wasm_simd);
257 config.wasm_relaxed_simd(semantics.wasm_simd);
258 config.wasm_bulk_memory(semantics.wasm_bulk_memory);
259 config.wasm_multi_value(semantics.wasm_multi_value);
260 config.wasm_multi_memory(false);
261 config.wasm_threads(false);
262 config.wasm_memory64(false);
263 config.wasm_tail_call(false);
264 config.wasm_extended_const(false);
265
266 let (use_pooling, use_cow) = match semantics.instantiation_strategy {
267 InstantiationStrategy::PoolingCopyOnWrite => (true, true),
268 InstantiationStrategy::Pooling => (true, false),
269 InstantiationStrategy::RecreateInstanceCopyOnWrite => (false, true),
270 InstantiationStrategy::RecreateInstance => (false, false),
271 };
272
273 const WASM_PAGE_SIZE: u64 = 65536;
274
275 config.memory_init_cow(use_cow);
276 config.memory_guaranteed_dense_image_size(match semantics.heap_alloc_strategy {
277 HeapAllocStrategy::Dynamic { maximum_pages } =>
278 maximum_pages.map(|p| p as u64 * WASM_PAGE_SIZE).unwrap_or(u64::MAX),
279 HeapAllocStrategy::Static { .. } => u64::MAX,
280 });
281
282 if use_pooling {
283 const MAX_WASM_PAGES: u64 = 0x10000;
284
285 let memory_pages = match semantics.heap_alloc_strategy {
286 HeapAllocStrategy::Dynamic { maximum_pages } =>
287 maximum_pages.map(|p| p as u64).unwrap_or(MAX_WASM_PAGES),
288 HeapAllocStrategy::Static { .. } => MAX_WASM_PAGES,
289 };
290
291 let mut pooling_config = wasmtime::PoolingAllocationConfig::default();
292 pooling_config
293 .max_unused_warm_slots(4)
294 .max_core_instance_size(512 * 1024)
302 .table_elements(8192)
303 .max_memory_size(memory_pages as usize * WASM_PAGE_SIZE as usize)
304 .total_tables(MAX_INSTANCE_COUNT)
305 .total_memories(MAX_INSTANCE_COUNT)
306 .total_core_instances(MAX_INSTANCE_COUNT);
309
310 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(pooling_config));
311 }
312
313 Ok(config)
314}
315
316#[derive(Clone)]
342pub struct DeterministicStackLimit {
343 pub logical_max: u32,
348 pub native_stack_max: u32,
359}
360
361#[non_exhaustive]
371#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
372pub enum InstantiationStrategy {
373 PoolingCopyOnWrite,
378
379 RecreateInstanceCopyOnWrite,
382
383 Pooling,
386
387 RecreateInstance,
389}
390
391enum InternalInstantiationStrategy {
392 Builtin,
393}
394
395#[derive(Clone)]
396pub struct Semantics {
397 pub instantiation_strategy: InstantiationStrategy,
399
400 pub deterministic_stack_limit: Option<DeterministicStackLimit>,
411
412 pub canonicalize_nans: bool,
425
426 pub parallel_compilation: bool,
428
429 pub heap_alloc_strategy: HeapAllocStrategy,
431
432 pub wasm_multi_value: bool,
434
435 pub wasm_bulk_memory: bool,
437
438 pub wasm_reference_types: bool,
440
441 pub wasm_simd: bool,
443}
444
445#[derive(Clone)]
446pub struct Config {
447 pub allow_missing_func_imports: bool,
452
453 pub cache_path: Option<PathBuf>,
455
456 pub semantics: Semantics,
458}
459
460enum CodeSupplyMode<'a> {
461 Fresh(RuntimeBlob),
463
464 Precompiled(&'a Path),
472
473 PrecompiledBytes(&'a [u8]),
478}
479
480pub fn create_runtime<H>(
486 blob: RuntimeBlob,
487 config: Config,
488) -> std::result::Result<WasmtimeRuntime, WasmError>
489where
490 H: HostFunctions,
491{
492 unsafe { do_create_runtime::<H>(CodeSupplyMode::Fresh(blob), config) }
494}
495
496pub unsafe fn create_runtime_from_artifact<H>(
513 compiled_artifact_path: &Path,
514 config: Config,
515) -> std::result::Result<WasmtimeRuntime, WasmError>
516where
517 H: HostFunctions,
518{
519 do_create_runtime::<H>(CodeSupplyMode::Precompiled(compiled_artifact_path), config)
520}
521
522pub unsafe fn create_runtime_from_artifact_bytes<H>(
538 compiled_artifact_bytes: &[u8],
539 config: Config,
540) -> std::result::Result<WasmtimeRuntime, WasmError>
541where
542 H: HostFunctions,
543{
544 do_create_runtime::<H>(CodeSupplyMode::PrecompiledBytes(compiled_artifact_bytes), config)
545}
546
547unsafe fn do_create_runtime<H>(
552 code_supply_mode: CodeSupplyMode<'_>,
553 mut config: Config,
554) -> std::result::Result<WasmtimeRuntime, WasmError>
555where
556 H: HostFunctions,
557{
558 replace_strategy_if_broken(&mut config.semantics.instantiation_strategy);
559
560 let mut wasmtime_config = common_config(&config.semantics)?;
561 if let Some(ref cache_path) = config.cache_path {
562 if let Err(reason) = setup_wasmtime_caching(cache_path, &mut wasmtime_config) {
563 log::warn!(
564 "failed to setup wasmtime cache. Performance may degrade significantly: {}.",
565 reason,
566 );
567 }
568 }
569
570 let engine = Engine::new(&wasmtime_config)
571 .map_err(|e| WasmError::Other(format!("cannot create the wasmtime engine: {:#}", e)))?;
572
573 let (module, instantiation_strategy) = match code_supply_mode {
574 CodeSupplyMode::Fresh(blob) => {
575 let blob = prepare_blob_for_compilation(blob, &config.semantics)?;
576 let serialized_blob = blob.clone().serialize();
577
578 let module = wasmtime::Module::new(&engine, &serialized_blob)
579 .map_err(|e| WasmError::Other(format!("cannot create module: {:#}", e)))?;
580
581 match config.semantics.instantiation_strategy {
582 InstantiationStrategy::Pooling |
583 InstantiationStrategy::PoolingCopyOnWrite |
584 InstantiationStrategy::RecreateInstance |
585 InstantiationStrategy::RecreateInstanceCopyOnWrite =>
586 (module, InternalInstantiationStrategy::Builtin),
587 }
588 },
589 CodeSupplyMode::Precompiled(compiled_artifact_path) => {
590 let module = wasmtime::Module::deserialize_file(&engine, compiled_artifact_path)
595 .map_err(|e| WasmError::Other(format!("cannot deserialize module: {:#}", e)))?;
596
597 (module, InternalInstantiationStrategy::Builtin)
598 },
599 CodeSupplyMode::PrecompiledBytes(compiled_artifact_bytes) => {
600 let module = wasmtime::Module::deserialize(&engine, compiled_artifact_bytes)
605 .map_err(|e| WasmError::Other(format!("cannot deserialize module: {:#}", e)))?;
606
607 (module, InternalInstantiationStrategy::Builtin)
608 },
609 };
610
611 let mut linker = wasmtime::Linker::new(&engine);
612 crate::imports::prepare_imports::<H>(&mut linker, &module, config.allow_missing_func_imports)?;
613
614 let instance_pre = linker
615 .instantiate_pre(&module)
616 .map_err(|e| WasmError::Other(format!("cannot preinstantiate module: {:#}", e)))?;
617
618 Ok(WasmtimeRuntime {
619 engine,
620 instance_pre: Arc::new(instance_pre),
621 instantiation_strategy,
622 instance_counter: Default::default(),
623 })
624}
625
626fn prepare_blob_for_compilation(
627 mut blob: RuntimeBlob,
628 semantics: &Semantics,
629) -> std::result::Result<RuntimeBlob, WasmError> {
630 if let Some(DeterministicStackLimit { logical_max, .. }) = semantics.deterministic_stack_limit {
631 blob = blob.inject_stack_depth_metering(logical_max)?;
632 }
633
634 blob.convert_memory_import_into_export()?;
639 blob.setup_memory_according_to_heap_alloc_strategy(semantics.heap_alloc_strategy)?;
640
641 Ok(blob)
642}
643
644pub fn prepare_runtime_artifact(
647 blob: RuntimeBlob,
648 semantics: &Semantics,
649) -> std::result::Result<Vec<u8>, WasmError> {
650 let mut semantics = semantics.clone();
651 replace_strategy_if_broken(&mut semantics.instantiation_strategy);
652
653 let blob = prepare_blob_for_compilation(blob, &semantics)?;
654
655 let engine = Engine::new(&common_config(&semantics)?)
656 .map_err(|e| WasmError::Other(format!("cannot create the engine: {:#}", e)))?;
657
658 engine
659 .precompile_module(&blob.serialize())
660 .map_err(|e| WasmError::Other(format!("cannot precompile module: {:#}", e)))
661}
662
663fn perform_call(
664 data: &[u8],
665 instance_wrapper: &mut InstanceWrapper,
666 entrypoint: EntryPoint,
667 mut allocator: FreeingBumpHeapAllocator,
668 allocation_stats: &mut Option<AllocationStats>,
669) -> Result<Vec<u8>> {
670 let (data_ptr, data_len) = inject_input_data(instance_wrapper, &mut allocator, data)?;
671
672 let host_state = HostState::new(allocator);
673
674 instance_wrapper.store_mut().data_mut().host_state = Some(host_state);
676
677 let ret = entrypoint
678 .call(instance_wrapper.store_mut(), data_ptr, data_len)
679 .map(unpack_ptr_and_len);
680
681 let host_state = instance_wrapper.store_mut().data_mut().host_state.take().expect(
683 "the host state is always set before calling into WASM so it can't be None here; qed",
684 );
685 *allocation_stats = Some(host_state.allocation_stats());
686
687 let (output_ptr, output_len) = ret?;
688 let output = extract_output_data(instance_wrapper, output_ptr, output_len)?;
689
690 Ok(output)
691}
692
693fn inject_input_data(
694 instance: &mut InstanceWrapper,
695 allocator: &mut FreeingBumpHeapAllocator,
696 data: &[u8],
697) -> Result<(Pointer<u8>, WordSize)> {
698 let mut ctx = instance.store_mut();
699 let memory = ctx.data().memory();
700 let data_len = data.len() as WordSize;
701 let data_ptr = allocator.allocate(&mut MemoryWrapper(&memory, &mut ctx), data_len)?;
702 util::write_memory_from(instance.store_mut(), data_ptr, data)?;
703 Ok((data_ptr, data_len))
704}
705
706fn extract_output_data(
707 instance: &InstanceWrapper,
708 output_ptr: u32,
709 output_len: u32,
710) -> Result<Vec<u8>> {
711 let ctx = instance.store();
712
713 let memory_size = ctx.as_context().data().memory().data_size(ctx);
719 if checked_range(output_ptr as usize, output_len as usize, memory_size).is_none() {
720 Err(Error::OutputExceedsBounds)?
721 }
722 let mut output = vec![0; output_len as usize];
723
724 util::read_memory_into(ctx, Pointer::new(output_ptr), &mut output)?;
725 Ok(output)
726}