1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
56// 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.
1011// 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.
1516// 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/>.
1819use crate::{runtime::StoreData, InstantiationStrategy};
20use sc_executor_common::{
21 error::{Error, Result},
22 util::checked_range,
23};
24use sp_wasm_interface::Pointer;
25use wasmtime::{AsContext, AsContextMut};
2627/// Read data from the instance memory into a slice.
28///
29/// Returns an error if the read would go out of the memory bounds.
30pub(crate) fn read_memory_into(
31 ctx: impl AsContext<Data = StoreData>,
32 address: Pointer<u8>,
33 dest: &mut [u8],
34) -> Result<()> {
35let memory = ctx.as_context().data().memory().data(&ctx);
3637let range = checked_range(address.into(), dest.len(), memory.len())
38 .ok_or_else(|| Error::Other("memory read is out of bounds".into()))?;
39 dest.copy_from_slice(&memory[range]);
40Ok(())
41}
4243/// Write data to the instance memory from a slice.
44///
45/// Returns an error if the write would go out of the memory bounds.
46pub(crate) fn write_memory_from(
47mut ctx: impl AsContextMut<Data = StoreData>,
48 address: Pointer<u8>,
49 data: &[u8],
50) -> Result<()> {
51let memory = ctx.as_context().data().memory();
52let memory = memory.data_mut(&mut ctx);
5354let range = checked_range(address.into(), data.len(), memory.len())
55 .ok_or_else(|| Error::Other("memory write is out of bounds".into()))?;
56 memory[range].copy_from_slice(data);
57Ok(())
58}
5960/// Checks whether the `madvise(MADV_DONTNEED)` works as expected.
61///
62/// In certain environments (e.g. when running under the QEMU user-mode emulator)
63/// this syscall is broken.
64#[cfg(target_os = "linux")]
65fn is_madvise_working() -> std::result::Result<bool, String> {
66let page_size = rustix::param::page_size();
6768unsafe {
69// Allocate two memory pages.
70let pointer = rustix::mm::mmap_anonymous(
71 std::ptr::null_mut(),
722 * page_size,
73 rustix::mm::ProtFlags::READ | rustix::mm::ProtFlags::WRITE,
74 rustix::mm::MapFlags::PRIVATE,
75 )
76 .map_err(|error| format!("mmap failed: {}", error))?;
7778// Dirty them both.
79std::ptr::write_volatile(pointer.cast::<u8>(), b'A');
80 std::ptr::write_volatile(pointer.cast::<u8>().add(page_size), b'B');
8182// Clear the first page.
83let result_madvise =
84 rustix::mm::madvise(pointer, page_size, rustix::mm::Advice::LinuxDontNeed)
85 .map_err(|error| format!("madvise failed: {}", error));
8687// Fetch the values.
88let value_1 = std::ptr::read_volatile(pointer.cast::<u8>());
89let value_2 = std::ptr::read_volatile(pointer.cast::<u8>().add(page_size));
9091let result_munmap = rustix::mm::munmap(pointer, 2 * page_size)
92 .map_err(|error| format!("munmap failed: {}", error));
9394 result_madvise?;
95 result_munmap?;
9697// Verify that the first page was cleared, while the second one was not.
98Ok(value_1 == 0 && value_2 == b'B')
99 }
100}
101102#[cfg(test)]
103#[cfg(target_os = "linux")]
104#[test]
105fn test_is_madvise_working_check_does_not_fail() {
106assert!(is_madvise_working().is_ok());
107}
108109/// Checks whether a given instantiation strategy can be safely used, and replaces
110/// it with a slower (but sound) alternative if it isn't.
111#[cfg(target_os = "linux")]
112pub(crate) fn replace_strategy_if_broken(strategy: &mut InstantiationStrategy) {
113let replacement_strategy = match *strategy {
114// These strategies don't need working `madvise`.
115InstantiationStrategy::Pooling | InstantiationStrategy::RecreateInstance => return,
116117// These strategies require a working `madvise` to be sound.
118InstantiationStrategy::PoolingCopyOnWrite => InstantiationStrategy::Pooling,
119 InstantiationStrategy::RecreateInstanceCopyOnWrite =>
120 InstantiationStrategy::RecreateInstance,
121 };
122123use std::sync::OnceLock;
124static IS_OK: OnceLock<bool> = OnceLock::new();
125126let is_ok = IS_OK.get_or_init(|| {
127let is_ok = match is_madvise_working() {
128Ok(is_ok) => is_ok,
129Err(error) => {
130// This should never happen.
131log::warn!("Failed to check whether `madvise(MADV_DONTNEED)` works: {}", error);
132false
133}
134 };
135136if !is_ok {
137log::warn!("You're running on a system with a broken `madvise(MADV_DONTNEED)` implementation. This will result in lower performance.");
138 }
139140 is_ok
141 });
142143if !is_ok {
144*strategy = replacement_strategy;
145 }
146}
147148#[cfg(not(target_os = "linux"))]
149pub(crate) fn replace_strategy_if_broken(_: &mut InstantiationStrategy) {}