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
pub use self::instrs::ResumableHostError;
pub(crate) use self::stack::Stack;
use self::{
    instrs::{dispatch_host_func, execute_instrs},
    stack::CallFrame,
};
use crate::{
    engine::{
        bytecode::{InstructionPtr, Register, RegisterSpan},
        CallParams,
        CallResults,
        EngineInner,
        ResumableCallBase,
        ResumableInvocation,
    },
    func::HostFuncEntity,
    Error,
    Func,
    FuncEntity,
    Store,
    StoreContextMut,
};

#[cfg(doc)]
use crate::engine::StackLimits;

use super::code_map::CodeMap;

mod cache;
mod instrs;
mod stack;

impl EngineInner {
    /// Executes the given [`Func`] with the given `params` and returns the `results`.
    ///
    /// Uses the [`StoreContextMut`] for context information about the Wasm [`Store`].
    ///
    /// # Errors
    ///
    /// If the Wasm execution traps or runs out of resources.
    pub fn execute_func<T, Results>(
        &self,
        ctx: StoreContextMut<T>,
        func: &Func,
        params: impl CallParams,
        results: Results,
    ) -> Result<<Results as CallResults>::Results, Error>
    where
        Results: CallResults,
    {
        let mut stack = self.stacks.lock().reuse_or_new();
        let results = EngineExecutor::new(&self.code_map, &mut stack)
            .execute_root_func(ctx.store, func, params, results)
            .map_err(|error| match error.into_resumable() {
                Ok(error) => error.into_error(),
                Err(error) => error,
            });
        self.stacks.lock().recycle(stack);
        results
    }

    /// Executes the given [`Func`] resumably with the given `params` and returns the `results`.
    ///
    /// Uses the [`StoreContextMut`] for context information about the Wasm [`Store`].
    ///
    /// # Errors
    ///
    /// If the Wasm execution traps or runs out of resources.
    pub fn execute_func_resumable<T, Results>(
        &self,
        ctx: StoreContextMut<T>,
        func: &Func,
        params: impl CallParams,
        results: Results,
    ) -> Result<ResumableCallBase<<Results as CallResults>::Results>, Error>
    where
        Results: CallResults,
    {
        let store = ctx.store;
        let mut stack = self.stacks.lock().reuse_or_new();
        let results = EngineExecutor::new(&self.code_map, &mut stack)
            .execute_root_func(store, func, params, results);
        match results {
            Ok(results) => {
                self.stacks.lock().recycle(stack);
                Ok(ResumableCallBase::Finished(results))
            }
            Err(error) => match error.into_resumable() {
                Ok(error) => {
                    let host_func = *error.host_func();
                    let caller_results = *error.caller_results();
                    let host_error = error.into_error();
                    Ok(ResumableCallBase::Resumable(ResumableInvocation::new(
                        store.engine().clone(),
                        *func,
                        host_func,
                        host_error,
                        caller_results,
                        stack,
                    )))
                }
                Err(error) => {
                    self.stacks.lock().recycle(stack);
                    Err(error)
                }
            },
        }
    }

    /// Resumes the given [`Func`] with the given `params` and returns the `results`.
    ///
    /// Uses the [`StoreContextMut`] for context information about the Wasm [`Store`].
    ///
    /// # Errors
    ///
    /// If the Wasm execution traps or runs out of resources.
    pub fn resume_func<T, Results>(
        &self,
        ctx: StoreContextMut<T>,
        mut invocation: ResumableInvocation,
        params: impl CallParams,
        results: Results,
    ) -> Result<ResumableCallBase<<Results as CallResults>::Results>, Error>
    where
        Results: CallResults,
    {
        let host_func = invocation.host_func();
        let caller_results = invocation.caller_results();
        let results = EngineExecutor::new(&self.code_map, &mut invocation.stack).resume_func(
            ctx.store,
            host_func,
            params,
            caller_results,
            results,
        );
        match results {
            Ok(results) => {
                self.stacks.lock().recycle(invocation.take_stack());
                Ok(ResumableCallBase::Finished(results))
            }
            Err(error) => match error.into_resumable() {
                Ok(error) => {
                    let host_func = *error.host_func();
                    let caller_results = *error.caller_results();
                    invocation.update(host_func, error.into_error(), caller_results);
                    Ok(ResumableCallBase::Resumable(invocation))
                }
                Err(error) => {
                    self.stacks.lock().recycle(invocation.take_stack());
                    Err(error)
                }
            },
        }
    }
}

/// The internal state of the Wasmi engine.
#[derive(Debug)]
pub struct EngineExecutor<'engine> {
    /// Shared and reusable generic engine resources.
    code_map: &'engine CodeMap,
    /// The value and call stacks.
    stack: &'engine mut Stack,
}

/// Convenience function that does nothing to its `&mut` parameter.
#[inline]
fn do_nothing<T>(_: &mut T) {}

impl<'engine> EngineExecutor<'engine> {
    /// Creates a new [`EngineExecutor`] with the given [`StackLimits`].
    fn new(code_map: &'engine CodeMap, stack: &'engine mut Stack) -> Self {
        Self { code_map, stack }
    }

    /// Executes the given [`Func`] using the given `params`.
    ///
    /// Stores the execution result into `results` upon a successful execution.
    ///
    /// # Errors
    ///
    /// - If the given `params` do not match the expected parameters of `func`.
    /// - If the given `results` do not match the the length of the expected results of `func`.
    /// - When encountering a Wasm or host trap during the execution of `func`.
    fn execute_root_func<T, Results>(
        &mut self,
        store: &mut Store<T>,
        func: &Func,
        params: impl CallParams,
        results: Results,
    ) -> Result<<Results as CallResults>::Results, Error>
    where
        Results: CallResults,
    {
        self.stack.reset();
        match store.inner.resolve_func(func) {
            FuncEntity::Wasm(wasm_func) => {
                // We reserve space on the stack to write the results of the root function execution.
                let len_results = results.len_results();
                self.stack.values.extend_by(len_results, do_nothing)?;
                let instance = *wasm_func.instance();
                let engine_func = wasm_func.func_body();
                let compiled_func = self
                    .code_map
                    .get(Some(store.inner.fuel_mut()), engine_func)?;
                let (mut uninit_params, offsets) = self
                    .stack
                    .values
                    .alloc_call_frame(compiled_func, do_nothing)?;
                for value in params.call_params() {
                    unsafe { uninit_params.init_next(value) };
                }
                uninit_params.init_zeroes();
                self.stack.calls.push(
                    CallFrame::new(
                        InstructionPtr::new(compiled_func.instrs().as_ptr()),
                        offsets,
                        RegisterSpan::new(Register::from_i16(0)),
                    ),
                    Some(instance),
                )?;
                self.execute_func(store)?;
            }
            FuncEntity::Host(host_func) => {
                // The host function signature is required for properly
                // adjusting, inspecting and manipulating the value stack.
                // In case the host function returns more values than it takes
                // we are required to extend the value stack.
                let len_params = host_func.len_params();
                let len_results = host_func.len_results();
                let max_inout = len_params.max(len_results);
                let uninit = self
                    .stack
                    .values
                    .extend_by(usize::from(max_inout), do_nothing)?;
                for (uninit, param) in uninit.iter_mut().zip(params.call_params()) {
                    uninit.write(param);
                }
                let host_func = *host_func;
                self.dispatch_host_func(store, host_func)?;
            }
        };
        let results = self.write_results_back(results);
        Ok(results)
    }

    /// Resumes the execution of the given [`Func`] using `params`.
    ///
    /// Stores the execution result into `results` upon a successful execution.
    ///
    /// # Errors
    ///
    /// - If the given `params` do not match the expected parameters of `func`.
    /// - If the given `results` do not match the the length of the expected results of `func`.
    /// - When encountering a Wasm or host trap during the execution of `func`.
    fn resume_func<T, Results>(
        &mut self,
        store: &mut Store<T>,
        _host_func: Func,
        params: impl CallParams,
        caller_results: RegisterSpan,
        results: Results,
    ) -> Result<<Results as CallResults>::Results, Error>
    where
        Results: CallResults,
    {
        let caller = self
            .stack
            .calls
            .peek()
            .expect("must have caller call frame on stack upon function resumption");
        let mut caller_sp = unsafe { self.stack.values.stack_ptr_at(caller.base_offset()) };
        let call_params = params.call_params();
        let len_params = call_params.len();
        for (result, param) in caller_results.iter(len_params).zip(call_params) {
            unsafe { caller_sp.set(result, param) };
        }
        self.execute_func(store)?;
        let results = self.write_results_back(results);
        Ok(results)
    }

    /// Executes the top most Wasm function on the [`Stack`] until the [`Stack`] is empty.
    ///
    /// # Errors
    ///
    /// When encountering a Wasm or host trap during execution.
    #[inline(always)]
    fn execute_func<T>(&mut self, store: &mut Store<T>) -> Result<(), Error> {
        execute_instrs(store, self.stack, self.code_map)
    }

    /// Convenience forwarder to [`dispatch_host_func`].
    #[inline(always)]
    fn dispatch_host_func<T>(
        &mut self,
        store: &mut Store<T>,
        host_func: HostFuncEntity,
    ) -> Result<(), Error> {
        dispatch_host_func(store, &mut self.stack.values, host_func, None)?;
        Ok(())
    }

    /// Writes the results of the function execution back into the `results` buffer.
    ///
    /// # Note
    ///
    /// The value stack is empty after this operation.
    ///
    /// # Panics
    ///
    /// - If the `results` buffer length does not match the remaining amount of stack values.
    #[inline(always)]
    fn write_results_back<Results>(&mut self, results: Results) -> <Results as CallResults>::Results
    where
        Results: CallResults,
    {
        let len_results = results.len_results();
        results.call_results(&self.stack.values.as_slice()[..len_results])
    }
}