Skip to main content

sc_executor_wasmtime/
runtime.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Defines the compiled Wasm runtime that uses Wasmtime internally.
20
21use 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	/// This will only be set when we call into the runtime.
51	pub(crate) host_state: Option<HostState>,
52	/// This will be always set once the store is initialized.
53	pub(crate) memory: Option<Memory>,
54}
55
56impl StoreData {
57	/// Returns a mutable reference to the host state.
58	pub fn host_state_mut(&mut self) -> Option<&mut HostState> {
59		self.host_state.as_mut()
60	}
61
62	/// Returns the host memory.
63	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
86/// A handle for releasing an instance acquired by [`InstanceCounter::acquire_instance`].
87pub(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/// Keeps track on the number of parallel instances.
103///
104/// The runtime cache keeps track on the number of parallel instances. The maximum number in the
105/// cache is less than what we have configured as [`MAX_INSTANCE_COUNT`] for wasmtime. However, the
106/// cache will create on demand instances if required. This instance counter will ensure that we are
107/// blocking when we are trying to create too many instances.
108#[derive(Default)]
109pub(crate) struct InstanceCounter {
110	counter: Mutex<u32>,
111	wait_for_instance: parking_lot::Condvar,
112}
113
114impl InstanceCounter {
115	/// Acquire an instance.
116	///
117	/// Blocks if there is no free instance available.
118	///
119	/// The returned [`ReleaseInstanceHandle`] should be dropped when the instance isn't used
120	/// anymore.
121	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
133/// A `WasmModule` implementation using wasmtime to compile the runtime module to machine code
134/// and execute the compiled code.
135pub 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
156/// A `WasmInstance` implementation that reuses compiled module and spawns instances
157/// to execute the compiled code.
158pub 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
194/// Prepare a directory structure and a config file to enable wasmtime caching.
195///
196/// In case of an error the caching will not be enabled.
197fn 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			// Remember if we have already logged a warning due to an unknown profiling strategy.
229			static UNKNOWN_PROFILING_STRATEGY: AtomicBool = AtomicBool::new(false);
230			// Make sure that the warning will not be relogged regularly.
231			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		// In `wasmtime` 0.35 the default stack size limit was changed from 1MB to 512KB.
243		//
244		// This broke at least one parachain which depended on the original 1MB limit,
245		// so here we restore it to what it was originally.
246		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	// Be clear and specific about the extensions we support. If an update brings new features
254	// they should be introduced here as well.
255	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		},
280		HeapAllocStrategy::Static { .. } => u64::MAX,
281	});
282
283	if use_pooling {
284		const MAX_WASM_PAGES: u64 = 0x10000;
285
286		let memory_pages = match semantics.heap_alloc_strategy {
287			HeapAllocStrategy::Dynamic { maximum_pages } => {
288				maximum_pages.map(|p| p as u64).unwrap_or(MAX_WASM_PAGES)
289			},
290			HeapAllocStrategy::Static { .. } => MAX_WASM_PAGES,
291		};
292
293		let mut pooling_config = wasmtime::PoolingAllocationConfig::default();
294		pooling_config
295			.max_unused_warm_slots(4)
296			// Pooling needs a bunch of hard limits to be set; if we go over
297			// any of these then the instantiation will fail.
298			//
299			// Current minimum values for kusama (as of 2022-04-14):
300			//   size: 32384
301			//   table_elements: 1249
302			//   memory_pages: 2070
303			.max_core_instance_size(512 * 1024)
304			.table_elements(8192)
305			.max_memory_size(memory_pages as usize * WASM_PAGE_SIZE as usize)
306			.total_tables(MAX_INSTANCE_COUNT)
307			.total_memories(MAX_INSTANCE_COUNT)
308			// This determines how many instances of the module can be
309			// instantiated in parallel from the same `Module`.
310			.total_core_instances(MAX_INSTANCE_COUNT);
311
312		config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(pooling_config));
313	}
314
315	Ok(config)
316}
317
318/// Knobs for deterministic stack height limiting.
319///
320/// The WebAssembly standard defines a call/value stack but it doesn't say anything about its
321/// size except that it has to be finite. The implementations are free to choose their own notion
322/// of limit: some may count the number of calls or values, others would rely on the host machine
323/// stack and trap on reaching a guard page.
324///
325/// This obviously is a source of non-determinism during execution. This feature can be used
326/// to instrument the code so that it will count the depth of execution in some deterministic
327/// way (the machine stack limit should be so high that the deterministic limit always triggers
328/// first).
329///
330/// The deterministic stack height limiting feature allows to instrument the code so that it will
331/// count the number of items that may be on the stack. This counting will only act as an rough
332/// estimate of the actual stack limit in wasmtime. This is because wasmtime measures it's stack
333/// usage in bytes.
334///
335/// The actual number of bytes consumed by a function is not trivial to compute  without going
336/// through full compilation. Therefore, it's expected that `native_stack_max` is greatly
337/// overestimated and thus never reached in practice. The stack overflow check introduced by the
338/// instrumentation and that relies on the logical item count should be reached first.
339///
340/// See [here][stack_height] for more details of the instrumentation
341///
342/// [stack_height]: https://github.com/paritytech/wasm-instrument/blob/master/src/stack_limiter/mod.rs
343#[derive(Clone)]
344pub struct DeterministicStackLimit {
345	/// A number of logical "values" that can be pushed on the wasm stack. A trap will be triggered
346	/// if exceeded.
347	///
348	/// A logical value is a local, an argument or a value pushed on operand stack.
349	pub logical_max: u32,
350	/// The maximum number of bytes for stack used by wasmtime JITed code.
351	///
352	/// It's not specified how much bytes will be consumed by a stack frame for a given wasm
353	/// function after translation into machine code. It is also not quite trivial.
354	///
355	/// Therefore, this number should be chosen conservatively. It must be so large so that it can
356	/// fit the [`logical_max`](Self::logical_max) logical values on the stack, according to the
357	/// current instrumentation algorithm.
358	///
359	/// This value cannot be 0.
360	pub native_stack_max: u32,
361}
362
363/// The instantiation strategy to use for the WASM executor.
364///
365/// All of the CoW strategies (with `CopyOnWrite` suffix) are only supported when either:
366///   a) we're running on Linux,
367///   b) we're running on an Unix-like system and we're precompiling
368///      our module beforehand and instantiating from a file.
369///
370/// If the CoW variant of a strategy is unsupported the executor will
371/// fall back to the non-CoW equivalent.
372#[non_exhaustive]
373#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
374pub enum InstantiationStrategy {
375	/// Pool the instances to avoid initializing everything from scratch
376	/// on each instantiation. Use copy-on-write memory when possible.
377	///
378	/// This is the fastest instantiation strategy.
379	PoolingCopyOnWrite,
380
381	/// Recreate the instance from scratch on every instantiation.
382	/// Use copy-on-write memory when possible.
383	RecreateInstanceCopyOnWrite,
384
385	/// Pool the instances to avoid initializing everything from scratch
386	/// on each instantiation.
387	Pooling,
388
389	/// Recreate the instance from scratch on every instantiation. Very slow.
390	RecreateInstance,
391}
392
393enum InternalInstantiationStrategy {
394	Builtin,
395}
396
397#[derive(Clone)]
398pub struct Semantics {
399	/// The instantiation strategy to use.
400	pub instantiation_strategy: InstantiationStrategy,
401
402	/// Specifying `Some` will enable deterministic stack height. That is, all executor
403	/// invocations will reach stack overflow at the exactly same point across different wasmtime
404	/// versions and architectures.
405	///
406	/// This is achieved by a combination of running an instrumentation pass on input code and
407	/// configuring wasmtime accordingly.
408	///
409	/// Since this feature depends on instrumentation, it can be set only if runtime is
410	/// instantiated using the runtime blob, e.g. using [`create_runtime`].
411	// I.e. if [`CodeSupplyMode::Verbatim`] is used.
412	pub deterministic_stack_limit: Option<DeterministicStackLimit>,
413
414	/// Controls whether wasmtime should compile floating point in a way that doesn't allow for
415	/// non-determinism.
416	///
417	/// By default, the wasm spec allows some local non-determinism wrt. certain floating point
418	/// operations. Specifically, those operations that are not defined to operate on bits (e.g.
419	/// fneg) can produce NaN values. The exact bit pattern for those is not specified and may
420	/// depend on the particular machine that executes wasmtime generated JITed machine code. That
421	/// is a source of non-deterministic values.
422	///
423	/// The classical runtime environment for Substrate allowed it and punted this on the runtime
424	/// developers. For PVFs, we want to ensure that execution is deterministic though. Therefore,
425	/// for PVF execution this flag is meant to be turned on.
426	pub canonicalize_nans: bool,
427
428	/// Configures wasmtime to use multiple threads for compiling.
429	pub parallel_compilation: bool,
430
431	/// The heap allocation strategy to use.
432	pub heap_alloc_strategy: HeapAllocStrategy,
433
434	/// Enables WASM Multi-Value proposal
435	pub wasm_multi_value: bool,
436
437	/// Enables WASM Bulk Memory Operations proposal
438	pub wasm_bulk_memory: bool,
439
440	/// Enables WASM Reference Types proposal
441	pub wasm_reference_types: bool,
442
443	/// Enables WASM Fixed-Width SIMD proposal
444	pub wasm_simd: bool,
445}
446
447#[derive(Clone)]
448pub struct Config {
449	/// The WebAssembly standard requires all imports of an instantiated module to be resolved,
450	/// otherwise, the instantiation fails. If this option is set to `true`, then this behavior is
451	/// overridden and imports that are requested by the module and not provided by the host
452	/// functions will be resolved using stubs. These stubs will trap upon a call.
453	pub allow_missing_func_imports: bool,
454
455	/// A directory in which wasmtime can store its compiled artifacts cache.
456	pub cache_path: Option<PathBuf>,
457
458	/// Tuning of various semantics of the wasmtime executor.
459	pub semantics: Semantics,
460}
461
462enum CodeSupplyMode<'a> {
463	/// The runtime is instantiated using the given runtime blob.
464	Fresh(RuntimeBlob),
465
466	/// The runtime is instantiated using a precompiled module at the given path.
467	///
468	/// This assumes that the code is already prepared for execution and the same `Config` was
469	/// used.
470	///
471	/// We use a `Path` here instead of simply passing a byte slice to allow `wasmtime` to
472	/// map the runtime's linear memory on supported platforms in a copy-on-write fashion.
473	Precompiled(&'a Path),
474
475	/// The runtime is instantiated using a precompiled module with the given bytes.
476	///
477	/// This assumes that the code is already prepared for execution and the same `Config` was
478	/// used.
479	PrecompiledBytes(&'a [u8]),
480}
481
482/// Create a new `WasmtimeRuntime` given the code. This function performs translation from Wasm to
483/// machine code, which can be computationally heavy.
484///
485/// The `H` generic parameter is used to statically pass a set of host functions which are exposed
486/// to the runtime.
487pub fn create_runtime<H>(
488	blob: RuntimeBlob,
489	config: Config,
490) -> std::result::Result<WasmtimeRuntime, WasmError>
491where
492	H: HostFunctions,
493{
494	// SAFETY: this is safe because it doesn't use `CodeSupplyMode::Precompiled`.
495	unsafe { do_create_runtime::<H>(CodeSupplyMode::Fresh(blob), config) }
496}
497
498/// The same as [`create_runtime`] but takes a path to a precompiled artifact,
499/// which makes this function considerably faster than [`create_runtime`].
500///
501/// # Safety
502///
503/// The caller must ensure that the compiled artifact passed here was:
504///   1) produced by [`prepare_runtime_artifact`],
505///   2) written to the disk as a file,
506///   3) was not modified,
507///   4) will not be modified while any runtime using this artifact is alive, or is being
508///      instantiated.
509///
510/// Failure to adhere to these requirements might lead to crashes and arbitrary code execution.
511///
512/// It is ok though if the compiled artifact was created by code of another version or with
513/// different configuration flags. In such case the caller will receive an `Err` deterministically.
514pub unsafe fn create_runtime_from_artifact<H>(
515	compiled_artifact_path: &Path,
516	config: Config,
517) -> std::result::Result<WasmtimeRuntime, WasmError>
518where
519	H: HostFunctions,
520{
521	do_create_runtime::<H>(CodeSupplyMode::Precompiled(compiled_artifact_path), config)
522}
523
524/// The same as [`create_runtime`] but takes the bytes of a precompiled artifact,
525/// which makes this function considerably faster than [`create_runtime`],
526/// but slower than the more optimized [`create_runtime_from_artifact`].
527/// This is especially slow on non-Linux Unix systems. Useful in very niche cases.
528///
529/// # Safety
530///
531/// The caller must ensure that the compiled artifact passed here was:
532///   1) produced by [`prepare_runtime_artifact`],
533///   2) was not modified,
534///
535/// Failure to adhere to these requirements might lead to crashes and arbitrary code execution.
536///
537/// It is ok though if the compiled artifact was created by code of another version or with
538/// different configuration flags. In such case the caller will receive an `Err` deterministically.
539pub unsafe fn create_runtime_from_artifact_bytes<H>(
540	compiled_artifact_bytes: &[u8],
541	config: Config,
542) -> std::result::Result<WasmtimeRuntime, WasmError>
543where
544	H: HostFunctions,
545{
546	do_create_runtime::<H>(CodeSupplyMode::PrecompiledBytes(compiled_artifact_bytes), config)
547}
548
549/// # Safety
550///
551/// This is only unsafe if called with [`CodeSupplyMode::Artifact`]. See
552/// [`create_runtime_from_artifact`] to get more details.
553unsafe fn do_create_runtime<H>(
554	code_supply_mode: CodeSupplyMode<'_>,
555	mut config: Config,
556) -> std::result::Result<WasmtimeRuntime, WasmError>
557where
558	H: HostFunctions,
559{
560	replace_strategy_if_broken(&mut config.semantics.instantiation_strategy);
561
562	let mut wasmtime_config = common_config(&config.semantics)?;
563	if let Some(ref cache_path) = config.cache_path {
564		if let Err(reason) = setup_wasmtime_caching(cache_path, &mut wasmtime_config) {
565			log::warn!(
566				"failed to setup wasmtime cache. Performance may degrade significantly: {}.",
567				reason,
568			);
569		}
570	}
571
572	let engine = Engine::new(&wasmtime_config)
573		.map_err(|e| WasmError::Other(format!("cannot create the wasmtime engine: {:#}", e)))?;
574
575	let (module, instantiation_strategy) = match code_supply_mode {
576		CodeSupplyMode::Fresh(blob) => {
577			let blob = prepare_blob_for_compilation(blob, &config.semantics)?;
578			let serialized_blob = blob.clone().serialize();
579
580			let module = wasmtime::Module::new(&engine, &serialized_blob)
581				.map_err(|e| WasmError::Other(format!("cannot create module: {:#}", e)))?;
582
583			match config.semantics.instantiation_strategy {
584				InstantiationStrategy::Pooling |
585				InstantiationStrategy::PoolingCopyOnWrite |
586				InstantiationStrategy::RecreateInstance |
587				InstantiationStrategy::RecreateInstanceCopyOnWrite => {
588					(module, InternalInstantiationStrategy::Builtin)
589				},
590			}
591		},
592		CodeSupplyMode::Precompiled(compiled_artifact_path) => {
593			// SAFETY: The unsafety of `deserialize_file` is covered by this function. The
594			//         responsibilities to maintain the invariants are passed to the caller.
595			//
596			//         See [`create_runtime_from_artifact`] for more details.
597			let module = wasmtime::Module::deserialize_file(&engine, compiled_artifact_path)
598				.map_err(|e| WasmError::Other(format!("cannot deserialize module: {:#}", e)))?;
599
600			(module, InternalInstantiationStrategy::Builtin)
601		},
602		CodeSupplyMode::PrecompiledBytes(compiled_artifact_bytes) => {
603			// SAFETY: The unsafety of `deserialize` is covered by this function. The
604			//         responsibilities to maintain the invariants are passed to the caller.
605			//
606			//         See [`create_runtime_from_artifact_bytes`] for more details.
607			let module = wasmtime::Module::deserialize(&engine, compiled_artifact_bytes)
608				.map_err(|e| WasmError::Other(format!("cannot deserialize module: {:#}", e)))?;
609
610			(module, InternalInstantiationStrategy::Builtin)
611		},
612	};
613
614	let mut linker = wasmtime::Linker::new(&engine);
615	crate::imports::prepare_imports::<H>(&mut linker, &module, config.allow_missing_func_imports)?;
616
617	let instance_pre = linker
618		.instantiate_pre(&module)
619		.map_err(|e| WasmError::Other(format!("cannot preinstantiate module: {:#}", e)))?;
620
621	Ok(WasmtimeRuntime {
622		engine,
623		instance_pre: Arc::new(instance_pre),
624		instantiation_strategy,
625		instance_counter: Default::default(),
626	})
627}
628
629fn prepare_blob_for_compilation(
630	mut blob: RuntimeBlob,
631	semantics: &Semantics,
632) -> std::result::Result<RuntimeBlob, WasmError> {
633	if let Some(DeterministicStackLimit { logical_max, .. }) = semantics.deterministic_stack_limit {
634		blob = blob.inject_stack_depth_metering(logical_max)?;
635	}
636
637	// We don't actually need the memory to be imported so we can just convert any memory
638	// import into an export with impunity. This simplifies our code since `wasmtime` will
639	// now automatically take care of creating the memory for us, and it is also necessary
640	// to enable `wasmtime`'s instance pooling. (Imported memories are ineligible for pooling.)
641	blob.convert_memory_import_into_export()?;
642	blob.setup_memory_according_to_heap_alloc_strategy(semantics.heap_alloc_strategy)?;
643
644	Ok(blob)
645}
646
647/// Takes a [`RuntimeBlob`] and precompiles it returning the serialized result of compilation. It
648/// can then be used for calling [`create_runtime`] avoiding long compilation times.
649pub fn prepare_runtime_artifact(
650	blob: RuntimeBlob,
651	semantics: &Semantics,
652) -> std::result::Result<Vec<u8>, WasmError> {
653	let mut semantics = semantics.clone();
654	replace_strategy_if_broken(&mut semantics.instantiation_strategy);
655
656	let blob = prepare_blob_for_compilation(blob, &semantics)?;
657
658	let engine = Engine::new(&common_config(&semantics)?)
659		.map_err(|e| WasmError::Other(format!("cannot create the engine: {:#}", e)))?;
660
661	engine
662		.precompile_module(&blob.serialize())
663		.map_err(|e| WasmError::Other(format!("cannot precompile module: {:#}", e)))
664}
665
666fn perform_call(
667	data: &[u8],
668	instance_wrapper: &mut InstanceWrapper,
669	entrypoint: EntryPoint,
670	mut allocator: FreeingBumpHeapAllocator,
671	allocation_stats: &mut Option<AllocationStats>,
672) -> Result<Vec<u8>> {
673	let (data_ptr, data_len) = inject_input_data(instance_wrapper, &mut allocator, data)?;
674
675	let host_state = HostState::new(allocator);
676
677	// Set the host state before calling into wasm.
678	instance_wrapper.store_mut().data_mut().host_state = Some(host_state);
679
680	let ret = entrypoint
681		.call(instance_wrapper.store_mut(), data_ptr, data_len)
682		.map(unpack_ptr_and_len);
683
684	// Reset the host state
685	let host_state = instance_wrapper.store_mut().data_mut().host_state.take().expect(
686		"the host state is always set before calling into WASM so it can't be None here; qed",
687	);
688	*allocation_stats = Some(host_state.allocation_stats());
689
690	let (output_ptr, output_len) = ret?;
691	let output = extract_output_data(instance_wrapper, output_ptr, output_len)?;
692
693	Ok(output)
694}
695
696fn inject_input_data(
697	instance: &mut InstanceWrapper,
698	allocator: &mut FreeingBumpHeapAllocator,
699	data: &[u8],
700) -> Result<(Pointer<u8>, WordSize)> {
701	let mut ctx = instance.store_mut();
702	let memory = ctx.data().memory();
703	let data_len = data.len() as WordSize;
704	let data_ptr = allocator.allocate(&mut MemoryWrapper(&memory, &mut ctx), data_len)?;
705	util::write_memory_from(instance.store_mut(), data_ptr, data)?;
706	Ok((data_ptr, data_len))
707}
708
709fn extract_output_data(
710	instance: &InstanceWrapper,
711	output_ptr: u32,
712	output_len: u32,
713) -> Result<Vec<u8>> {
714	let ctx = instance.store();
715
716	// Do a length check before allocating. The returned output should not be bigger than the
717	// available WASM memory. Otherwise, a malicious parachain can trigger a large allocation,
718	// potentially causing memory exhaustion.
719	//
720	// Get the size of the WASM memory in bytes.
721	let memory_size = ctx.as_context().data().memory().data_size(ctx);
722	if checked_range(output_ptr as usize, output_len as usize, memory_size).is_none() {
723		Err(Error::OutputExceedsBounds)?
724	}
725	let mut output = vec![0; output_len as usize];
726
727	util::read_memory_into(ctx, Pointer::new(output_ptr), &mut output)?;
728	Ok(output)
729}