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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// This file is part of Gear.

// Copyright (C) 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/>.

//! Module that contains functions to check code.

use crate::{
    code::errors::*,
    message::{DispatchKind, WasmEntryPoint},
    pages::{WasmPage, WasmPagesAmount},
};
use alloc::collections::BTreeSet;
use gear_wasm_instrument::{
    parity_wasm::elements::{
        ExportEntry, External, GlobalEntry, ImportCountType, InitExpr, Instruction, Internal,
        Module, Type, ValueType,
    },
    SyscallName, STACK_END_EXPORT_NAME,
};

/// Defines maximal permitted count of memory pages.
pub const MAX_WASM_PAGES_AMOUNT: u16 = 512;

/// Name of exports allowed on chain.
pub const ALLOWED_EXPORTS: [&str; 6] = [
    "init",
    "handle",
    "handle_reply",
    "handle_signal",
    "state",
    "metahash",
];

/// Name of exports required on chain (only 1 of these is required).
pub const REQUIRED_EXPORTS: [&str; 2] = ["init", "handle"];

pub fn get_static_pages(module: &Module) -> Result<WasmPagesAmount, CodeError> {
    // get initial memory size from memory import
    let static_pages = module
        .import_section()
        .ok_or(SectionError::NotFound(SectionName::Import))?
        .entries()
        .iter()
        .find_map(|entry| match entry.external() {
            External::Memory(mem_ty) => Some(mem_ty.limits().initial()),
            _ => None,
        })
        .map(WasmPagesAmount::try_from)
        .ok_or(MemoryError::EntryNotFound)?
        .map_err(|_| MemoryError::InvalidStaticPageCount)?;

    if static_pages > WasmPagesAmount::from(MAX_WASM_PAGES_AMOUNT) {
        Err(MemoryError::InvalidStaticPageCount)?;
    }

    Ok(static_pages)
}

pub fn get_exports(module: &Module) -> BTreeSet<DispatchKind> {
    let mut entries = BTreeSet::new();

    for entry in module
        .export_section()
        .expect("Exports section has been checked for already")
        .entries()
        .iter()
    {
        if let Internal::Function(_) = entry.internal() {
            if let Some(entry) = DispatchKind::try_from_entry(entry.field()) {
                entries.insert(entry);
            }
        }
    }

    entries
}

pub fn check_exports(module: &Module) -> Result<(), CodeError> {
    let types = module
        .type_section()
        .ok_or(SectionError::NotFound(SectionName::Type))?
        .types();

    let funcs = module
        .function_section()
        .ok_or(SectionError::NotFound(SectionName::Function))?
        .entries();

    let import_count = module.import_count(ImportCountType::Function) as u32;

    let exports = module
        .export_section()
        .ok_or(SectionError::NotFound(SectionName::Export))?
        .entries();

    let mut entry_point_found = false;
    for (export_index, export) in exports.iter().enumerate() {
        let &Internal::Function(func_index) = export.internal() else {
            continue;
        };

        let index = func_index.checked_sub(import_count).ok_or(
            ExportError::ExportReferencesToImportFunction(export_index as u32, func_index),
        )?;

        // Panic is impossible, unless the Module structure is invalid.
        let type_id = funcs
            .get(index as usize)
            .unwrap_or_else(|| unreachable!("Module structure is invalid"))
            .type_ref() as usize;

        // Panic is impossible, unless the Module structure is invalid.
        let Type::Function(func_type) = types
            .get(type_id)
            .unwrap_or_else(|| unreachable!("Module structure is invalid"));

        if !ALLOWED_EXPORTS.contains(&export.field()) {
            Err(ExportError::ExcessExport(export_index as u32))?;
        }

        if !(func_type.params().is_empty() && func_type.results().is_empty()) {
            Err(ExportError::InvalidExportFnSignature(export_index as u32))?;
        }

        if REQUIRED_EXPORTS.contains(&export.field()) {
            entry_point_found = true;
        }
    }

    entry_point_found
        .then_some(())
        .ok_or(ExportError::RequiredExportNotFound)
        .map_err(CodeError::Export)
}

pub fn check_imports(module: &Module) -> Result<(), CodeError> {
    let types = module
        .type_section()
        .ok_or(SectionError::NotFound(SectionName::Type))?
        .types();

    let imports = module
        .import_section()
        .ok_or(SectionError::NotFound(SectionName::Import))?
        .entries();

    let syscalls = SyscallName::instrumentable_map();

    let mut visited_imports = BTreeSet::new();

    for (import_index, import) in imports.iter().enumerate() {
        let import_index: u32 = import_index
            .try_into()
            .unwrap_or_else(|_| unreachable!("Import index should fit in u32"));

        match import.external() {
            External::Function(i) => {
                // Panic is impossible, unless the Module structure is invalid.
                let Type::Function(func_type) = &types
                    .get(*i as usize)
                    .unwrap_or_else(|| unreachable!("Module structure is invalid"));

                let syscall = syscalls
                    .get(import.field())
                    .ok_or(ImportError::UnknownImport(import_index))?;

                if !visited_imports.insert(*syscall) {
                    Err(ImportError::DuplicateImport(import_index))?;
                }

                let signature = syscall.signature();

                let params = signature
                    .params()
                    .iter()
                    .copied()
                    .map(Into::<ValueType>::into);
                let results = signature.results().unwrap_or(&[]);

                if !(params.eq(func_type.params().iter().copied())
                    && results == func_type.results())
                {
                    Err(ImportError::InvalidImportFnSignature(import_index))?;
                }
            }
            External::Global(_) => Err(ImportError::UnexpectedImportKind {
                kind: &"Global",
                index: import_index,
            })?,
            External::Table(_) => Err(ImportError::UnexpectedImportKind {
                kind: &"Table",
                index: import_index,
            })?,
            _ => continue,
        }
    }

    Ok(())
}

fn get_export_entry_with_index<'a>(
    module: &'a Module,
    name: &str,
) -> Option<(u32, &'a ExportEntry)> {
    module
        .export_section()?
        .entries()
        .iter()
        .enumerate()
        .find_map(|(export_index, export)| {
            (export.field() == name).then_some((export_index as u32, export))
        })
}

fn get_export_global_with_index(module: &Module, name: &str) -> Option<(u32, u32)> {
    let (export_index, export) = get_export_entry_with_index(module, name)?;
    match export.internal() {
        Internal::Global(index) => Some((export_index, *index)),
        _ => None,
    }
}

fn get_init_expr_const_i32(init_expr: &InitExpr) -> Option<i32> {
    match init_expr.code() {
        [Instruction::I32Const(const_i32), Instruction::End] => Some(*const_i32),
        _ => None,
    }
}

fn get_export_global_entry(
    module: &Module,
    export_index: u32,
    global_index: u32,
) -> Result<&GlobalEntry, CodeError> {
    let index = (global_index as usize)
        .checked_sub(module.import_count(ImportCountType::Global))
        .ok_or(ExportError::ExportReferencesToImportGlobal(
            export_index,
            global_index,
        ))?;

    module
        .global_section()
        .and_then(|s| s.entries().get(index))
        .ok_or(ExportError::IncorrectGlobalIndex(global_index, export_index).into())
}

/// Check that data segments are not overlapping with stack and are inside static pages.
pub fn check_data_section(
    module: &Module,
    static_pages: WasmPagesAmount,
    stack_end: Option<WasmPage>,
    data_section_amount_limit: Option<u32>,
) -> Result<(), CodeError> {
    let Some(data_section) = module.data_section() else {
        // No data section - nothing to check.
        return Ok(());
    };

    // Check that data segments amount does not exceed the limit.
    if let Some(data_segments_amount_limit) = data_section_amount_limit {
        let number_of_data_segments = data_section.entries().len() as u32;
        if number_of_data_segments > data_segments_amount_limit {
            Err(DataSectionError::DataSegmentsAmountLimit {
                limit: data_segments_amount_limit,
                actual: number_of_data_segments,
            })?;
        }
    }

    for data_segment in data_section.entries() {
        let data_segment_offset = data_segment
            .offset()
            .as_ref()
            .and_then(get_init_expr_const_i32)
            .ok_or(DataSectionError::Initialization)? as u32;

        if let Some(stack_end_offset) = stack_end.map(|p| p.offset()) {
            // Checks, that each data segment does not overlap the user stack.
            (data_segment_offset >= stack_end_offset)
                .then_some(())
                .ok_or(DataSectionError::GearStackOverlaps(
                    data_segment_offset,
                    stack_end_offset,
                ))?;
        }

        let Some(size) = u32::try_from(data_segment.value().len())
            .map_err(|_| DataSectionError::EndAddressOverflow(data_segment_offset))?
            .checked_sub(1)
        else {
            // Zero size data segment - strange, but allowed.
            continue;
        };

        let data_segment_last_byte_offset = data_segment_offset
            .checked_add(size)
            .ok_or(DataSectionError::EndAddressOverflow(data_segment_offset))?;

        ((data_segment_last_byte_offset as u64) < static_pages.offset())
            .then_some(())
            .ok_or(DataSectionError::EndAddressOutOfStaticMemory(
                data_segment_offset,
                data_segment_last_byte_offset,
                static_pages.offset(),
            ))?;
    }

    Ok(())
}

fn get_stack_end_offset(module: &Module) -> Result<Option<u32>, CodeError> {
    let Some((export_index, global_index)) =
        get_export_global_with_index(module, STACK_END_EXPORT_NAME)
    else {
        return Ok(None);
    };

    Ok(Some(
        get_init_expr_const_i32(
            get_export_global_entry(module, export_index, global_index)?.init_expr(),
        )
        .ok_or(StackEndError::Initialization)? as u32,
    ))
}

pub fn check_and_canonize_gear_stack_end(
    module: &mut Module,
    static_pages: WasmPagesAmount,
) -> Result<Option<WasmPage>, CodeError> {
    let Some(stack_end_offset) = get_stack_end_offset(module)? else {
        return Ok(None);
    };

    // Remove stack end export from module.
    // Panic below is impossible, because we have checked above, that export section exists.
    module
        .export_section_mut()
        .unwrap_or_else(|| unreachable!("Cannot find export section"))
        .entries_mut()
        .retain(|export| export.field() != STACK_END_EXPORT_NAME);

    if stack_end_offset % WasmPage::SIZE != 0 {
        return Err(StackEndError::NotAligned(stack_end_offset).into());
    }

    let stack_end = WasmPage::from_offset(stack_end_offset);
    if stack_end > static_pages {
        return Err(StackEndError::OutOfStatic(stack_end_offset, static_pages.offset()).into());
    }

    Ok(Some(stack_end))
}

/// Checks that module:
/// 1) Does not have exports to mutable globals.
/// 2) Does not have exports to imported globals.
/// 3) Does not have exports with incorrect global index.
pub fn check_mut_global_exports(module: &Module) -> Result<(), CodeError> {
    let Some(export_section) = module.export_section() else {
        return Ok(());
    };

    export_section
        .entries()
        .iter()
        .enumerate()
        .filter_map(|(export_index, export)| match export.internal() {
            Internal::Global(index) => Some((export_index as u32, *index)),
            _ => None,
        })
        .try_for_each(|(export_index, global_index)| {
            let entry = get_export_global_entry(module, export_index, global_index)?;
            if entry.global_type().is_mutable() {
                Err(ExportError::MutableGlobalExport(global_index, export_index).into())
            } else {
                Ok(())
            }
        })
}

pub fn check_start_section(module: &Module) -> Result<(), CodeError> {
    if module.start_section().is_some() {
        log::debug!("Found start section in program code, which is not allowed");
        Err(SectionError::NotSupported(SectionName::Start))?
    } else {
        Ok(())
    }
}