1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
// This file is part of Gear.

// Copyright (C) 2022-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Lazy pages support for runtime.

#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

use byteorder::{ByteOrder, LittleEndian};
use core::fmt;
use gear_core::{
    ids::ProgramId,
    memory::{HostPointer, Memory, MemoryInterval},
    pages::{GearPage, PageNumber, PageU32Size, WasmPage},
    program::MemoryInfix,
};
use gear_lazy_pages_common::{GlobalsAccessConfig, LazyPagesWeights, ProcessAccessError, Status};
use gear_runtime_interface::{gear_ri, LazyPagesProgramContext};
use sp_std::{mem, vec::Vec};

fn mprotect_lazy_pages(mem: &mut impl Memory, protect: bool) {
    if mem.get_buffer_host_addr().is_none() {
        return;
    }

    // Cannot panic, unless OS has some problems with pages protection.
    gear_ri::mprotect_lazy_pages(protect);
}

/// Try to enable and initialize lazy pages env
pub fn try_to_enable_lazy_pages(prefix: [u8; 32]) -> bool {
    gear_ri::init_lazy_pages(gear_lazy_pages_common::LazyPagesInitContext::new(prefix).into())
}

/// Protect and save storage keys for pages which has no data
pub fn init_for_program(
    mem: &mut impl Memory,
    program_id: ProgramId,
    memory_infix: MemoryInfix,
    stack_end: Option<WasmPage>,
    globals_config: GlobalsAccessConfig,
    weights: LazyPagesWeights,
) {
    let weights = [
        weights.signal_read,
        weights.signal_write,
        weights.signal_write_after_read,
        weights.host_func_read,
        weights.host_func_write,
        weights.host_func_write_after_read,
        weights.load_page_storage_data,
    ]
    .map(|w| w.one())
    .to_vec();

    let ctx = LazyPagesProgramContext {
        wasm_mem_addr: mem.get_buffer_host_addr(),
        wasm_mem_size: mem.size().raw(),
        stack_end: stack_end.map(|p| p.raw()),
        program_key: {
            let memory_infix = memory_infix.inner().to_le_bytes();

            [program_id.as_ref(), memory_infix.as_ref()].concat()
        },
        globals_config,
        weights,
    };

    // Cannot panic unless OS allocates buffer in not aligned by native page addr, or
    // something goes wrong with pages protection.
    gear_ri::init_lazy_pages_for_program(ctx);
}

/// Remove lazy-pages protection, returns wasm memory begin addr
pub fn remove_lazy_pages_prot(mem: &mut impl Memory) {
    mprotect_lazy_pages(mem, false);
}

/// Protect lazy-pages and set new wasm mem addr and size,
/// if they have been changed.
pub fn update_lazy_pages_and_protect_again(
    mem: &mut impl Memory,
    old_mem_addr: Option<HostPointer>,
    old_mem_size: WasmPage,
    new_mem_addr: HostPointer,
) {
    struct PointerDisplay(HostPointer);

    impl fmt::Debug for PointerDisplay {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "{:#x}", self.0)
        }
    }

    let changed_addr = if old_mem_addr
        .map(|addr| new_mem_addr != addr)
        .unwrap_or(true)
    {
        log::debug!(
            "backend executor has changed wasm mem buff: from {:?} to {:?}",
            old_mem_addr.map(PointerDisplay),
            new_mem_addr
        );

        Some(new_mem_addr)
    } else {
        None
    };

    let new_mem_size = mem.size();
    let changed_size = (new_mem_size > old_mem_size).then_some(new_mem_size.raw());

    if !matches!((changed_addr, changed_size), (None, None)) {
        gear_ri::change_wasm_memory_addr_and_size(changed_addr, changed_size)
    }

    mprotect_lazy_pages(mem, true);
}

/// Returns list of released pages numbers.
pub fn get_write_accessed_pages() -> Vec<GearPage> {
    gear_ri::write_accessed_pages()
        .into_iter()
        .map(|p| {
            GearPage::new(p)
                .unwrap_or_else(|_| unreachable!("Lazy pages backend returns wrong pages"))
        })
        .collect()
}

/// Returns lazy pages actual status.
pub fn get_status() -> Status {
    gear_ri::lazy_pages_status().0
}

fn serialize_mem_intervals(intervals: &[MemoryInterval]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(mem::size_of_val(intervals));
    for interval in intervals {
        bytes.extend_from_slice(&interval.to_bytes());
    }
    bytes
}

/// Pre-process memory access in syscalls in lazy-pages.
pub fn pre_process_memory_accesses(
    reads: &[MemoryInterval],
    writes: &[MemoryInterval],
    gas_counter: &mut u64,
) -> Result<(), ProcessAccessError> {
    let serialized_reads = serialize_mem_intervals(reads);
    let serialized_writes = serialize_mem_intervals(writes);

    let mut gas_bytes = [0u8; 8];
    LittleEndian::write_u64(&mut gas_bytes, *gas_counter);

    let res =
        gear_ri::pre_process_memory_accesses(&serialized_reads, &serialized_writes, &mut gas_bytes);

    *gas_counter = LittleEndian::read_u64(&gas_bytes);

    // if result can be converted to `ProcessAccessError` then it's an error
    if let Ok(err) = ProcessAccessError::try_from(res) {
        return Err(err);
    }
    Ok(())
}