Skip to main content

mnemosyne_core/
policy.rs

1//! Compile-time allocator behaviors and memory safety policies.
2
3#[doc(hidden)]
4pub mod private {
5    pub trait Sealed {}
6}
7
8/// A sealed trait representing an allocator behavior and safety policy.
9pub trait AllocPolicy: private::Sealed + Send + Sync + 'static {
10    /// If true, write poison bytes to memory on allocation and deallocation to detect heap corruption.
11    const ENABLE_POISONING: bool;
12
13    /// If true, zero-initialize all memory allocations.
14    const ZERO_INITIALIZE: bool;
15
16    /// Byte pattern to write into memory when it is freed.
17    const POISON_FREE_BYTE: u8 = 0xDE;
18
19    /// Byte pattern to write into memory when it is allocated.
20    const POISON_ALLOC_BYTE: u8 = 0xAD;
21
22    /// If true, encrypt free list next pointers.
23    const ENABLE_FREE_LIST_ENCRYPTION: bool = false;
24
25    /// If true, randomize the allocation order of blocks in a page.
26    const RANDOMIZE_ALLOCATION: bool = false;
27}
28
29/// Zero-Sized Type (ZST) representing the standard allocation policy with maximum performance.
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
31pub struct StandardPolicy;
32
33impl private::Sealed for StandardPolicy {}
34impl AllocPolicy for StandardPolicy {
35    const ENABLE_POISONING: bool = false;
36    const ZERO_INITIALIZE: bool = false;
37}
38
39/// Zero-Sized Type (ZST) representing a secure allocation policy with memory
40/// poisoning and zero-initialization.
41#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
42pub struct SecurePolicy;
43
44impl private::Sealed for SecurePolicy {}
45impl AllocPolicy for SecurePolicy {
46    const ENABLE_POISONING: bool = true;
47    const ZERO_INITIALIZE: bool = true;
48    const RANDOMIZE_ALLOCATION: bool = true;
49}
50
51/// Zero-Sized Type (ZST) representing a hardened allocation policy with memory
52/// poisoning, zero-initialization, and free-list encryption.
53#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
54pub struct HardenedPolicy;
55
56impl private::Sealed for HardenedPolicy {}
57impl AllocPolicy for HardenedPolicy {
58    const ENABLE_POISONING: bool = true;
59    const ZERO_INITIALIZE: bool = true;
60    const ENABLE_FREE_LIST_ENCRYPTION: bool = true;
61    const RANDOMIZE_ALLOCATION: bool = true;
62}