1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
34// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
89// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
1314// You should have received a copy of the GNU General Public License
15// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
1617//! Interface to the Substrate Executor
1819use crate::error::ExecuteError;
20use polkadot_primitives::{
21 executor_params::{DEFAULT_LOGICAL_STACK_MAX, DEFAULT_NATIVE_STACK_MAX},
22 ExecutorParam, ExecutorParams,
23};
24use sc_executor_common::{
25 error::WasmError,
26 runtime_blob::RuntimeBlob,
27 wasm_runtime::{HeapAllocStrategy, WasmModule as _},
28};
29use sc_executor_wasmtime::{Config, DeterministicStackLimit, Semantics, WasmtimeRuntime};
30use sp_core::storage::{ChildInfo, TrackedStorageKey};
31use sp_externalities::MultiRemovalResults;
32use std::any::{Any, TypeId};
3334// Memory configuration
35//
36// When Substrate Runtime is instantiated, a number of WASM pages are allocated for the Substrate
37// Runtime instance's linear memory. The exact number of pages is a sum of whatever the WASM blob
38// itself requests (by default at least enough to hold the data section as well as have some space
39// left for the stack; this is, of course, overridable at link time when compiling the runtime)
40// plus the number of pages specified in the `extra_heap_pages` passed to the executor.
41//
42// By default, rustc (or `lld` specifically) should allocate 1 MiB for the shadow stack, or 16
43// pages. The data section for runtimes are typically rather small and can fit in a single digit
44// number of WASM pages, so let's say an extra 16 pages. Thus let's assume that 32 pages or 2 MiB
45// are used for these needs by default.
46const DEFAULT_HEAP_PAGES_ESTIMATE: u32 = 32;
47const EXTRA_HEAP_PAGES: u32 = 2048;
4849// VALUES OF THE DEFAULT CONFIGURATION SHOULD NEVER BE CHANGED
50// They are used as base values for the execution environment parametrization.
51// To overwrite them, add new ones to `EXECUTOR_PARAMS` in the `session_info` pallet and perform
52// a runtime upgrade to make them active.
53pub const DEFAULT_CONFIG: Config = Config {
54 allow_missing_func_imports: true,
55 cache_path: None,
56 semantics: Semantics {
57 heap_alloc_strategy: sc_executor_common::wasm_runtime::HeapAllocStrategy::Dynamic {
58 maximum_pages: Some(DEFAULT_HEAP_PAGES_ESTIMATE + EXTRA_HEAP_PAGES),
59 },
6061 instantiation_strategy:
62 sc_executor_wasmtime::InstantiationStrategy::RecreateInstanceCopyOnWrite,
6364// Enable deterministic stack limit to pin down the exact number of items the wasmtime stack
65 // can contain before it traps with stack overflow.
66 //
67 // Here is how the values below were chosen.
68 //
69 // At the moment of writing, the default native stack size limit is 1 MiB. Assuming a
70 // logical item (see the docs about the field and the instrumentation algorithm) is 8 bytes,
71 // 1 MiB can fit 2x 65536 logical items.
72 //
73 // Since reaching the native stack limit is undesirable, we halve the logical item limit and
74 // also increase the native 256x. This hopefully should preclude wasm code from reaching
75 // the stack limit set by the wasmtime.
76deterministic_stack_limit: Some(DeterministicStackLimit {
77 logical_max: DEFAULT_LOGICAL_STACK_MAX,
78 native_stack_max: DEFAULT_NATIVE_STACK_MAX,
79 }),
80 canonicalize_nans: true,
81// Rationale for turning the multi-threaded compilation off is to make the preparation time
82 // easily reproducible and as deterministic as possible.
83 //
84 // Currently the prepare queue doesn't distinguish between precheck and prepare requests.
85 // On the one hand, it simplifies the code, on the other, however, slows down compile times
86 // for execute requests. This behavior may change in future.
87parallel_compilation: false,
8889// WASM extensions. Only those that are meaningful to us may be controlled here. By default,
90 // we're using WASM MVP, which means all the extensions are disabled. Nevertheless, some
91 // extensions (e.g., sign extension ops) are enabled by Wasmtime and cannot be disabled.
92wasm_reference_types: false,
93 wasm_simd: false,
94 wasm_bulk_memory: false,
95 wasm_multi_value: false,
96 },
97};
9899/// Executes the given PVF in the form of a compiled artifact and returns the result of
100/// execution upon success.
101///
102/// # Safety
103///
104/// The caller must ensure that the compiled artifact passed here was:
105/// 1) produced by `prepare`,
106/// 2) was not modified,
107///
108/// Failure to adhere to these requirements might lead to crashes and arbitrary code execution.
109pub unsafe fn execute_artifact(
110 compiled_artifact_blob: &[u8],
111 executor_params: &ExecutorParams,
112 params: &[u8],
113) -> Result<Vec<u8>, ExecuteError> {
114let mut extensions = sp_externalities::Extensions::new();
115116 extensions.register(sp_core::traits::ReadRuntimeVersionExt::new(ReadRuntimeVersion));
117118let mut ext = ValidationExternalities(extensions);
119120match sc_executor::with_externalities_safe(&mut ext, || {
121let runtime = create_runtime_from_artifact_bytes(compiled_artifact_blob, executor_params)?;
122 runtime.new_instance()?.call("validate_block", params)
123 }) {
124Ok(Ok(ok)) => Ok(ok),
125Ok(Err(err)) | Err(err) => Err(err),
126 }
127}
128129/// Constructs the runtime for the given PVF, given the artifact bytes.
130///
131/// # Safety
132///
133/// The caller must ensure that the compiled artifact passed here was:
134/// 1) produced by `prepare`,
135/// 2) was not modified,
136///
137/// Failure to adhere to these requirements might lead to crashes and arbitrary code execution.
138pub unsafe fn create_runtime_from_artifact_bytes(
139 compiled_artifact_blob: &[u8],
140 executor_params: &ExecutorParams,
141) -> Result<WasmtimeRuntime, WasmError> {
142let mut config = DEFAULT_CONFIG.clone();
143 config.semantics = params_to_wasmtime_semantics(executor_params).0;
144145 sc_executor_wasmtime::create_runtime_from_artifact_bytes::<HostFunctions>(
146 compiled_artifact_blob,
147 config,
148 )
149}
150151/// Takes the default config and overwrites any settings with existing executor parameters.
152///
153/// Returns the semantics as well as the stack limit (since we are guaranteed to have it).
154pub fn params_to_wasmtime_semantics(par: &ExecutorParams) -> (Semantics, DeterministicStackLimit) {
155let mut sem = DEFAULT_CONFIG.semantics.clone();
156let mut stack_limit = sem
157 .deterministic_stack_limit
158 .expect("There is a comment to not change the default stack limit; it should always be available; qed")
159 .clone();
160161for p in par.iter() {
162match p {
163 ExecutorParam::MaxMemoryPages(max_pages) =>
164 sem.heap_alloc_strategy = HeapAllocStrategy::Dynamic {
165 maximum_pages: Some((*max_pages).saturating_add(DEFAULT_HEAP_PAGES_ESTIMATE)),
166 },
167 ExecutorParam::StackLogicalMax(slm) => stack_limit.logical_max = *slm,
168 ExecutorParam::StackNativeMax(snm) => stack_limit.native_stack_max = *snm,
169 ExecutorParam::WasmExtBulkMemory => sem.wasm_bulk_memory = true,
170 ExecutorParam::PrecheckingMaxMemory(_) |
171 ExecutorParam::PvfPrepTimeout(_, _) |
172 ExecutorParam::PvfExecTimeout(_, _) => (), /* Not used here */
173}
174 }
175 sem.deterministic_stack_limit = Some(stack_limit.clone());
176 (sem, stack_limit)
177}
178179/// Runs the prevalidation on the given code. Returns a [`RuntimeBlob`] if it succeeds.
180pub fn prevalidate(code: &[u8]) -> Result<RuntimeBlob, sc_executor_common::error::WasmError> {
181// Construct the runtime blob and do some basic checks for consistency.
182let blob = RuntimeBlob::new(code)?;
183// In the future this function should take care of any further prevalidation logic.
184Ok(blob)
185}
186187/// Runs preparation on the given runtime blob. If successful, it returns a serialized compiled
188/// artifact which can then be used to pass into `Executor::execute` after writing it to the disk.
189pub fn prepare(
190 blob: RuntimeBlob,
191 executor_params: &ExecutorParams,
192) -> Result<Vec<u8>, sc_executor_common::error::WasmError> {
193let (semantics, _) = params_to_wasmtime_semantics(executor_params);
194 sc_executor_wasmtime::prepare_runtime_artifact(blob, &semantics)
195}
196197/// Available host functions. We leave out:
198///
199/// 1. storage related stuff (PVF doesn't have a notion of a persistent storage/trie)
200/// 2. tracing
201/// 3. off chain workers (PVFs do not have such a notion)
202/// 4. runtime tasks
203/// 5. sandbox
204type HostFunctions = (
205 sp_io::misc::HostFunctions,
206 sp_io::crypto::HostFunctions,
207 sp_io::hashing::HostFunctions,
208 sp_io::allocator::HostFunctions,
209 sp_io::logging::HostFunctions,
210 sp_io::trie::HostFunctions,
211);
212213/// The validation externalities that will panic on any storage related access. (PVFs should not
214/// have a notion of a persistent storage/trie.)
215struct ValidationExternalities(sp_externalities::Extensions);
216217impl sp_externalities::Externalities for ValidationExternalities {
218fn storage(&mut self, _: &[u8]) -> Option<Vec<u8>> {
219panic!("storage: unsupported feature for parachain validation")
220 }
221222fn storage_hash(&mut self, _: &[u8]) -> Option<Vec<u8>> {
223panic!("storage_hash: unsupported feature for parachain validation")
224 }
225226fn child_storage_hash(&mut self, _: &ChildInfo, _: &[u8]) -> Option<Vec<u8>> {
227panic!("child_storage_hash: unsupported feature for parachain validation")
228 }
229230fn child_storage(&mut self, _: &ChildInfo, _: &[u8]) -> Option<Vec<u8>> {
231panic!("child_storage: unsupported feature for parachain validation")
232 }
233234fn kill_child_storage(
235&mut self,
236 _child_info: &ChildInfo,
237 _maybe_limit: Option<u32>,
238 _maybe_cursor: Option<&[u8]>,
239 ) -> MultiRemovalResults {
240panic!("kill_child_storage: unsupported feature for parachain validation")
241 }
242243fn clear_prefix(
244&mut self,
245 _prefix: &[u8],
246 _maybe_limit: Option<u32>,
247 _maybe_cursor: Option<&[u8]>,
248 ) -> MultiRemovalResults {
249panic!("clear_prefix: unsupported feature for parachain validation")
250 }
251252fn clear_child_prefix(
253&mut self,
254 _child_info: &ChildInfo,
255 _prefix: &[u8],
256 _maybe_limit: Option<u32>,
257 _maybe_cursor: Option<&[u8]>,
258 ) -> MultiRemovalResults {
259panic!("clear_child_prefix: unsupported feature for parachain validation")
260 }
261262fn place_storage(&mut self, _: Vec<u8>, _: Option<Vec<u8>>) {
263panic!("place_storage: unsupported feature for parachain validation")
264 }
265266fn place_child_storage(&mut self, _: &ChildInfo, _: Vec<u8>, _: Option<Vec<u8>>) {
267panic!("place_child_storage: unsupported feature for parachain validation")
268 }
269270fn storage_root(&mut self, _: sp_core::storage::StateVersion) -> Vec<u8> {
271panic!("storage_root: unsupported feature for parachain validation")
272 }
273274fn child_storage_root(&mut self, _: &ChildInfo, _: sp_core::storage::StateVersion) -> Vec<u8> {
275panic!("child_storage_root: unsupported feature for parachain validation")
276 }
277278fn next_child_storage_key(&mut self, _: &ChildInfo, _: &[u8]) -> Option<Vec<u8>> {
279panic!("next_child_storage_key: unsupported feature for parachain validation")
280 }
281282fn next_storage_key(&mut self, _: &[u8]) -> Option<Vec<u8>> {
283panic!("next_storage_key: unsupported feature for parachain validation")
284 }
285286fn storage_append(&mut self, _key: Vec<u8>, _value: Vec<u8>) {
287panic!("storage_append: unsupported feature for parachain validation")
288 }
289290fn storage_start_transaction(&mut self) {
291panic!("storage_start_transaction: unsupported feature for parachain validation")
292 }
293294fn storage_rollback_transaction(&mut self) -> Result<(), ()> {
295panic!("storage_rollback_transaction: unsupported feature for parachain validation")
296 }
297298fn storage_commit_transaction(&mut self) -> Result<(), ()> {
299panic!("storage_commit_transaction: unsupported feature for parachain validation")
300 }
301302fn wipe(&mut self) {
303panic!("wipe: unsupported feature for parachain validation")
304 }
305306fn commit(&mut self) {
307panic!("commit: unsupported feature for parachain validation")
308 }
309310fn read_write_count(&self) -> (u32, u32, u32, u32) {
311panic!("read_write_count: unsupported feature for parachain validation")
312 }
313314fn reset_read_write_count(&mut self) {
315panic!("reset_read_write_count: unsupported feature for parachain validation")
316 }
317318fn get_whitelist(&self) -> Vec<TrackedStorageKey> {
319panic!("get_whitelist: unsupported feature for parachain validation")
320 }
321322fn set_whitelist(&mut self, _: Vec<TrackedStorageKey>) {
323panic!("set_whitelist: unsupported feature for parachain validation")
324 }
325326fn set_offchain_storage(&mut self, _: &[u8], _: std::option::Option<&[u8]>) {
327panic!("set_offchain_storage: unsupported feature for parachain validation")
328 }
329330fn get_read_and_written_keys(&self) -> Vec<(Vec<u8>, u32, u32, bool)> {
331panic!("get_read_and_written_keys: unsupported feature for parachain validation")
332 }
333}
334335impl sp_externalities::ExtensionStore for ValidationExternalities {
336fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> {
337self.0.get_mut(type_id)
338 }
339340fn register_extension_with_type_id(
341&mut self,
342 type_id: TypeId,
343 extension: Box<dyn sp_externalities::Extension>,
344 ) -> Result<(), sp_externalities::Error> {
345self.0.register_with_type_id(type_id, extension)
346 }
347348fn deregister_extension_by_type_id(
349&mut self,
350 type_id: TypeId,
351 ) -> Result<(), sp_externalities::Error> {
352if self.0.deregister(type_id) {
353Ok(())
354 } else {
355Err(sp_externalities::Error::ExtensionIsNotRegistered(type_id))
356 }
357 }
358}
359360struct ReadRuntimeVersion;
361362impl sp_core::traits::ReadRuntimeVersion for ReadRuntimeVersion {
363fn read_runtime_version(
364&self,
365 wasm_code: &[u8],
366 _ext: &mut dyn sp_externalities::Externalities,
367 ) -> Result<Vec<u8>, String> {
368let blob = RuntimeBlob::uncompress_if_needed(wasm_code)
369 .map_err(|e| format!("Failed to read the PVF runtime blob: {:?}", e))?;
370371match sc_executor::read_embedded_version(&blob)
372 .map_err(|e| format!("Failed to read the static section from the PVF blob: {:?}", e))?
373{
374Some(version) => {
375use codec::Encode;
376Ok(version.encode())
377 },
378None => Err("runtime version section is not found".to_string()),
379 }
380 }
381}