sc_allocator/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Collection of allocator implementations.
19//!
20//! This crate provides the following allocator implementations:
21//! - A freeing-bump allocator: [`FreeingBumpHeapAllocator`]
22
23#![warn(missing_docs)]
24
25mod error;
26mod freeing_bump;
27
28pub use error::Error;
29pub use freeing_bump::{AllocationStats, FreeingBumpHeapAllocator};
30
31/// The size of one wasm page in bytes.
32///
33/// The wasm memory is divided into pages, meaning the minimum size of a memory is one page.
34const PAGE_SIZE: u32 = 65536;
35
36/// The maximum number of wasm pages that can be allocated.
37///
38/// 4GiB / [`PAGE_SIZE`].
39const MAX_WASM_PAGES: u32 = (4u64 * 1024 * 1024 * 1024 / PAGE_SIZE as u64) as u32;
40
41/// Grants access to the memory for the allocator.
42///
43/// Memory of wasm is allocated in pages. A page has a constant size of 64KiB. The maximum allowed
44/// memory size as defined in the wasm specification is 4GiB (65536 pages).
45pub trait Memory {
46 /// Run the given closure `run` and grant it write access to the raw memory.
47 fn with_access_mut<R>(&mut self, run: impl FnOnce(&mut [u8]) -> R) -> R;
48 /// Run the given closure `run` and grant it read access to the raw memory.
49 fn with_access<R>(&self, run: impl FnOnce(&[u8]) -> R) -> R;
50 /// Grow the memory by `additional` pages.
51 fn grow(&mut self, additional: u32) -> Result<(), ()>;
52 /// Returns the current number of pages this memory has allocated.
53 fn pages(&self) -> u32;
54 /// Returns the maximum number of pages this memory is allowed to allocate.
55 ///
56 /// The returned number needs to be smaller or equal to `65536`. The returned number needs to be
57 /// bigger or equal to [`Self::pages`].
58 ///
59 /// If `None` is returned, there is no maximum (besides the maximum defined in the wasm spec).
60 fn max_pages(&self) -> Option<u32>;
61}