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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! The Wasmi interpreter.

mod block_type;
pub mod bytecode;
mod cache;
mod code_map;
mod config;
mod executor;
mod func_args;
mod func_types;
mod limits;
mod resumable;
mod traits;
mod translator;

#[cfg(test)]
mod tests;

#[cfg(test)]
use self::bytecode::RegisterSpan;

pub(crate) use self::{
    block_type::BlockType,
    config::FuelCosts,
    executor::Stack,
    func_args::{FuncFinished, FuncParams, FuncResults},
    func_types::DedupFuncType,
    translator::{
        FuncTranslationDriver,
        FuncTranslator,
        FuncTranslatorAllocations,
        LazyFuncTranslator,
        ValidatingFuncTranslator,
        WasmTranslator,
    },
};
pub use self::{
    code_map::CompiledFunc,
    config::{CompilationMode, Config},
    executor::ResumableHostError,
    limits::{EnforcedLimits, EnforcedLimitsError, StackLimits},
    resumable::{ResumableCall, ResumableInvocation, TypedResumableCall, TypedResumableInvocation},
    traits::{CallParams, CallResults},
    translator::{Instr, TranslationError},
};
use self::{
    code_map::{CodeMap, CompiledFuncEntity},
    func_types::FuncTypeRegistry,
    resumable::ResumableCallBase,
};
use crate::{
    collections::arena::{ArenaIndex, GuardedEntity},
    module::{FuncIdx, ModuleHeader},
    Error,
    Func,
    FuncType,
    StoreContextMut,
};
use core::sync::atomic::{AtomicU32, Ordering};
use spin::{Mutex, RwLock};
use std::{
    sync::{Arc, Weak},
    vec::Vec,
};
use wasmparser::{FuncToValidate, FuncValidatorAllocations, ValidatorResources};

#[cfg(test)]
use self::bytecode::Instruction;

#[cfg(test)]
use crate::core::UntypedVal;

#[cfg(doc)]
use crate::Store;

/// A unique engine index.
///
/// # Note
///
/// Used to protect against invalid entity indices.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct EngineIdx(u32);

impl ArenaIndex for EngineIdx {
    fn into_usize(self) -> usize {
        self.0 as _
    }

    fn from_usize(value: usize) -> Self {
        let value = value.try_into().unwrap_or_else(|error| {
            panic!("index {value} is out of bounds as engine index: {error}")
        });
        Self(value)
    }
}

impl EngineIdx {
    /// Returns a new unique [`EngineIdx`].
    fn new() -> Self {
        /// A static store index counter.
        static CURRENT_STORE_IDX: AtomicU32 = AtomicU32::new(0);
        let next_idx = CURRENT_STORE_IDX.fetch_add(1, Ordering::AcqRel);
        Self(next_idx)
    }
}

/// An entity owned by the [`Engine`].
type Guarded<Idx> = GuardedEntity<EngineIdx, Idx>;

/// The Wasmi interpreter.
///
/// # Note
///
/// - The current Wasmi engine implements a bytecode interpreter.
/// - This structure is intentionally cheap to copy.
///   Most of its API has a `&self` receiver, so can be shared easily.
#[derive(Debug, Clone)]
pub struct Engine {
    inner: Arc<EngineInner>,
}

/// A weak reference to an [`Engine`].
#[derive(Debug, Clone)]
pub struct EngineWeak {
    inner: Weak<EngineInner>,
}

impl EngineWeak {
    /// Upgrades the [`EngineWeak`] to an [`Engine`].
    ///
    /// Returns `None` if strong references (the [`Engine`] itself) no longer exist.
    pub fn upgrade(&self) -> Option<Engine> {
        let inner = self.inner.upgrade()?;
        Some(Engine { inner })
    }
}

impl Default for Engine {
    fn default() -> Self {
        Self::new(&Config::default())
    }
}

impl Engine {
    /// Creates a new [`Engine`] with default configuration.
    ///
    /// # Note
    ///
    /// Users should ues [`Engine::default`] to construct a default [`Engine`].
    pub fn new(config: &Config) -> Self {
        Self {
            inner: Arc::new(EngineInner::new(config)),
        }
    }

    /// Creates an [`EngineWeak`] from the given [`Engine`].
    pub fn weak(&self) -> EngineWeak {
        EngineWeak {
            inner: Arc::downgrade(&self.inner),
        }
    }

    /// Returns a shared reference to the [`Config`] of the [`Engine`].
    pub fn config(&self) -> &Config {
        self.inner.config()
    }

    /// Returns `true` if both [`Engine`] references `a` and `b` refer to the same [`Engine`].
    pub fn same(a: &Engine, b: &Engine) -> bool {
        Arc::ptr_eq(&a.inner, &b.inner)
    }

    /// Allocates a new function type to the [`Engine`].
    pub(super) fn alloc_func_type(&self, func_type: FuncType) -> DedupFuncType {
        self.inner.alloc_func_type(func_type)
    }

    /// Resolves a deduplicated function type into a [`FuncType`] entity.
    ///
    /// # Panics
    ///
    /// - If the deduplicated function type is not owned by the engine.
    /// - If the deduplicated function type cannot be resolved to its entity.
    pub(super) fn resolve_func_type<F, R>(&self, func_type: &DedupFuncType, f: F) -> R
    where
        F: FnOnce(&FuncType) -> R,
    {
        self.inner.resolve_func_type(func_type, f)
    }

    /// Allocates a new uninitialized [`CompiledFunc`] to the [`Engine`].
    ///
    /// Returns a [`CompiledFunc`] reference to allow accessing the allocated [`CompiledFunc`].
    pub(super) fn alloc_func(&self) -> CompiledFunc {
        self.inner.alloc_func()
    }

    /// Translates the Wasm function using the [`Engine`].
    ///
    /// - Uses the internal [`Config`] to drive the function translation as mandated.
    /// - Reuses translation and validation allocations to be more efficient when used for many translation units.
    ///
    /// # Parameters
    ///
    /// - `func_index`: The index of the translated function within its Wasm module.
    /// - `compiled_func`: The index of the translated function in the [`Engine`].
    /// - `offset`: The global offset of the Wasm function body within the Wasm binary.
    /// - `bytes`: The bytes that make up the Wasm encoded function body of the translated function.
    /// - `module`: The module header information of the Wasm module of the translated function.
    /// - `func_to_validate`: Optionally validates the translated function.
    ///
    /// # Errors
    ///
    /// - If function translation fails.
    /// - If function validation fails.
    pub(crate) fn translate_func(
        &self,
        func_index: FuncIdx,
        compiled_func: CompiledFunc,
        offset: usize,
        bytes: &[u8],
        module: ModuleHeader,
        func_to_validate: Option<FuncToValidate<ValidatorResources>>,
    ) -> Result<(), Error> {
        match (self.config().get_compilation_mode(), func_to_validate) {
            (CompilationMode::Eager, Some(func_to_validate)) => {
                let (translation_allocs, validation_allocs) = self.inner.get_allocs();
                let validator = func_to_validate.into_validator(validation_allocs);
                let translator = FuncTranslator::new(func_index, module, translation_allocs)?;
                let translator = ValidatingFuncTranslator::new(validator, translator)?;
                let allocs = FuncTranslationDriver::new(offset, bytes, translator)?
                    .translate(|func_entity| self.inner.init_func(compiled_func, func_entity))?;
                self.inner
                    .recycle_allocs(allocs.translation, allocs.validation);
            }
            (CompilationMode::Eager, None) => {
                let allocs = self.inner.get_translation_allocs();
                let translator = FuncTranslator::new(func_index, module, allocs)?;
                let allocs = FuncTranslationDriver::new(offset, bytes, translator)?
                    .translate(|func_entity| self.inner.init_func(compiled_func, func_entity))?;
                self.inner.recycle_translation_allocs(allocs);
            }
            (CompilationMode::LazyTranslation, Some(func_to_validate)) => {
                let allocs = self.inner.get_validation_allocs();
                let translator = LazyFuncTranslator::new(func_index, compiled_func, module, None);
                let validator = func_to_validate.into_validator(allocs);
                let translator = ValidatingFuncTranslator::new(validator, translator)?;
                let allocs = FuncTranslationDriver::new(offset, bytes, translator)?
                    .translate(|func_entity| self.inner.init_func(compiled_func, func_entity))?;
                self.inner.recycle_validation_allocs(allocs.validation);
            }
            (CompilationMode::Lazy | CompilationMode::LazyTranslation, func_to_validate) => {
                let translator =
                    LazyFuncTranslator::new(func_index, compiled_func, module, func_to_validate);
                FuncTranslationDriver::new(offset, bytes, translator)?
                    .translate(|func_entity| self.inner.init_func(compiled_func, func_entity))?;
            }
        }
        Ok(())
    }

    /// Returns reusable [`FuncTranslatorAllocations`] from the [`Engine`].
    pub(crate) fn get_translation_allocs(&self) -> FuncTranslatorAllocations {
        self.inner.get_translation_allocs()
    }

    /// Returns reusable [`FuncTranslatorAllocations`] and [`FuncValidatorAllocations`] from the [`Engine`].
    pub(crate) fn get_allocs(&self) -> (FuncTranslatorAllocations, FuncValidatorAllocations) {
        self.inner.get_allocs()
    }

    /// Recycles the given [`FuncTranslatorAllocations`] in the [`Engine`].
    pub(crate) fn recycle_translation_allocs(&self, allocs: FuncTranslatorAllocations) {
        self.inner.recycle_translation_allocs(allocs)
    }

    /// Recycles the given [`FuncTranslatorAllocations`] and [`FuncValidatorAllocations`] in the [`Engine`].
    pub(crate) fn recycle_allocs(
        &self,
        translation: FuncTranslatorAllocations,
        validation: FuncValidatorAllocations,
    ) {
        self.inner.recycle_allocs(translation, validation)
    }

    /// Initializes the uninitialized [`CompiledFunc`] for the [`Engine`].
    ///
    /// # Note
    ///
    /// The initialized function will not be compiled after this call and instead
    /// be prepared to be compiled on the fly when it is called the first time.
    ///
    /// # Panics
    ///
    /// - If `func` is an invalid [`CompiledFunc`] reference for this [`CodeMap`].
    /// - If `func` refers to an already initialized [`CompiledFunc`].
    fn init_lazy_func(
        &self,
        func_idx: FuncIdx,
        func: CompiledFunc,
        bytes: &[u8],
        module: &ModuleHeader,
        func_to_validate: Option<FuncToValidate<ValidatorResources>>,
    ) {
        self.inner
            .init_lazy_func(func_idx, func, bytes, module, func_to_validate)
    }

    /// Resolves the [`CompiledFunc`] to the underlying Wasmi bytecode instructions.
    ///
    /// # Note
    ///
    /// - This is a variant of [`Engine::resolve_instr`] that returns register
    ///   machine based bytecode instructions.
    /// - This API is mainly intended for unit testing purposes and shall not be used
    ///   outside of this context. The function bodies are intended to be data private
    ///   to the Wasmi interpreter.
    ///
    /// # Errors
    ///
    /// If the `func` fails Wasm to Wasmi bytecode translation after it was lazily initialized.
    ///
    /// # Panics
    ///
    /// - If the [`CompiledFunc`] is invalid for the [`Engine`].
    /// - If register machine bytecode translation is disabled.
    #[cfg(test)]
    pub(crate) fn resolve_instr(
        &self,
        func: CompiledFunc,
        index: usize,
    ) -> Result<Option<Instruction>, Error> {
        self.inner.resolve_instr(func, index)
    }

    /// Resolves the function local constant of [`CompiledFunc`] at `index` if any.
    ///
    /// # Note
    ///
    /// This API is intended for unit testing purposes and shall not be used
    /// outside of this context. The function bodies are intended to be data
    /// private to the Wasmi interpreter.
    ///
    /// # Errors
    ///
    /// If the `func` fails Wasm to Wasmi bytecode translation after it was lazily initialized.
    ///
    /// # Panics
    ///
    /// - If the [`CompiledFunc`] is invalid for the [`Engine`].
    /// - If register machine bytecode translation is disabled.
    #[cfg(test)]
    fn get_func_const(
        &self,
        func: CompiledFunc,
        index: usize,
    ) -> Result<Option<UntypedVal>, Error> {
        self.inner.get_func_const(func, index)
    }

    /// Executes the given [`Func`] with parameters `params`.
    ///
    /// Stores the execution result into `results` upon a successful execution.
    ///
    /// # Note
    ///
    /// - Assumes that the `params` and `results` are well typed.
    ///   Type checks are done at the [`Func::call`] API or when creating
    ///   a new [`TypedFunc`] instance via [`Func::typed`].
    /// - The `params` out parameter is in a valid but unspecified state if this
    ///   function returns with an error.
    ///
    /// # Errors
    ///
    /// - If `params` are overflowing or underflowing the expected amount of parameters.
    /// - 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`.
    ///
    /// [`TypedFunc`]: [`crate::TypedFunc`]
    #[inline]
    pub(crate) 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,
    {
        self.inner.execute_func(ctx, func, params, results)
    }

    /// Executes the given [`Func`] resumably with parameters `params` and returns.
    ///
    /// Stores the execution result into `results` upon a successful execution.
    /// If the execution encounters a host trap it will return a handle to the user
    /// that allows to resume the execution at that point.
    ///
    /// # Note
    ///
    /// - Assumes that the `params` and `results` are well typed.
    ///   Type checks are done at the [`Func::call`] API or when creating
    ///   a new [`TypedFunc`] instance via [`Func::typed`].
    /// - The `params` out parameter is in a valid but unspecified state if this
    ///   function returns with an error.
    ///
    /// # Errors
    ///
    /// - If `params` are overflowing or underflowing the expected amount of parameters.
    /// - If the given `results` do not match the the length of the expected results of `func`.
    /// - When encountering a Wasm trap during the execution of `func`.
    /// - When `func` is a host function that traps.
    ///
    /// [`TypedFunc`]: [`crate::TypedFunc`]
    #[inline]
    pub(crate) 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,
    {
        self.inner
            .execute_func_resumable(ctx, func, params, results)
    }

    /// Resumes the given `invocation` given the `params`.
    ///
    /// Stores the execution result into `results` upon a successful execution.
    /// If the execution encounters a host trap it will return a handle to the user
    /// that allows to resume the execution at that point.
    ///
    /// # Note
    ///
    /// - Assumes that the `params` and `results` are well typed.
    ///   Type checks are done at the [`Func::call`] API or when creating
    ///   a new [`TypedFunc`] instance via [`Func::typed`].
    /// - The `params` out parameter is in a valid but unspecified state if this
    ///   function returns with an error.
    ///
    /// # Errors
    ///
    /// - If `params` are overflowing or underflowing the expected amount of parameters.
    /// - If the given `results` do not match the the length of the expected results of `func`.
    /// - When encountering a Wasm trap during the execution of `func`.
    /// - When `func` is a host function that traps.
    ///
    /// [`TypedFunc`]: [`crate::TypedFunc`]
    #[inline]
    pub(crate) fn resume_func<T, Results>(
        &self,
        ctx: StoreContextMut<T>,
        invocation: ResumableInvocation,
        params: impl CallParams,
        results: Results,
    ) -> Result<ResumableCallBase<<Results as CallResults>::Results>, Error>
    where
        Results: CallResults,
    {
        self.inner.resume_func(ctx, invocation, params, results)
    }

    /// Recycles the given [`Stack`] for reuse in the [`Engine`].
    pub(crate) fn recycle_stack(&self, stack: Stack) {
        self.inner.recycle_stack(stack)
    }
}

/// The internal state of the Wasmi [`Engine`].
#[derive(Debug)]
pub struct EngineInner {
    /// The [`Config`] of the engine.
    config: Config,
    /// Engine resources shared across multiple engine executors.
    res: RwLock<EngineResources>,
    /// Reusable allocation stacks.
    allocs: Mutex<ReusableAllocationStack>,
    /// Reusable engine stacks for Wasm execution.
    ///
    /// Concurrently executing Wasm executions each require their own stack to
    /// operate on. Therefore a Wasm engine is required to provide stacks and
    /// ideally recycles old ones since creation of a new stack is rather expensive.
    stacks: Mutex<EngineStacks>,
}

/// Stacks to hold and distribute reusable allocations.
pub struct ReusableAllocationStack {
    /// The maximum height of each of the allocations stacks.
    max_height: usize,
    /// Allocations required by Wasm function translators.
    translation: Vec<FuncTranslatorAllocations>,
    /// Allocations required by Wasm function validators.
    validation: Vec<FuncValidatorAllocations>,
}

impl Default for ReusableAllocationStack {
    fn default() -> Self {
        Self {
            max_height: 1,
            translation: Vec::new(),
            validation: Vec::new(),
        }
    }
}

impl core::fmt::Debug for ReusableAllocationStack {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("ReusableAllocationStack")
            .field("translation", &self.translation)
            // Note: FuncValidatorAllocations is missing Debug impl at the time of writing this commit.
            //       We should derive Debug as soon as FuncValidatorAllocations has a Debug impl in future
            //       wasmparser versions.
            .field("validation", &self.validation.len())
            .finish()
    }
}

impl ReusableAllocationStack {
    /// Returns reusable [`FuncTranslatorAllocations`] from the [`Engine`].
    pub fn get_translation_allocs(&mut self) -> FuncTranslatorAllocations {
        self.translation.pop().unwrap_or_default()
    }

    /// Returns reusable [`FuncValidatorAllocations`] from the [`Engine`].
    pub fn get_validation_allocs(&mut self) -> FuncValidatorAllocations {
        self.validation.pop().unwrap_or_default()
    }

    /// Recycles the given [`FuncTranslatorAllocations`] in the [`Engine`].
    pub fn recycle_translation_allocs(&mut self, recycled: FuncTranslatorAllocations) {
        debug_assert!(self.translation.len() <= self.max_height);
        if self.translation.len() >= self.max_height {
            return;
        }
        self.translation.push(recycled);
    }

    /// Recycles the given [`FuncValidatorAllocations`] in the [`Engine`].
    pub fn recycle_validation_allocs(&mut self, recycled: FuncValidatorAllocations) {
        debug_assert!(self.validation.len() <= self.max_height);
        if self.validation.len() >= self.max_height {
            return;
        }
        self.validation.push(recycled);
    }
}

/// The engine's stacks for reuse.
///
/// Rquired for efficient concurrent Wasm executions.
#[derive(Debug)]
pub struct EngineStacks {
    /// Stacks to be (re)used.
    stacks: Vec<Stack>,
    /// Stack limits for newly constructed engine stacks.
    limits: StackLimits,
    /// How many stacks should be kept for reuse at most.
    keep: usize,
}

impl EngineStacks {
    /// Creates new [`EngineStacks`] with the given [`StackLimits`].
    pub fn new(config: &Config) -> Self {
        Self {
            stacks: Vec::new(),
            limits: config.stack_limits(),
            keep: config.cached_stacks(),
        }
    }

    /// Reuse or create a new [`Stack`] if none was available.
    pub fn reuse_or_new(&mut self) -> Stack {
        match self.stacks.pop() {
            Some(stack) => stack,
            None => Stack::new(self.limits),
        }
    }

    /// Disose and recycle the `stack`.
    pub fn recycle(&mut self, stack: Stack) {
        if stack.capacity() > 0 && self.stacks.len() < self.keep {
            self.stacks.push(stack);
        }
    }
}

impl EngineInner {
    /// Creates a new [`EngineInner`] with the given [`Config`].
    fn new(config: &Config) -> Self {
        Self {
            config: *config,
            res: RwLock::new(EngineResources::new(config)),
            allocs: Mutex::new(ReusableAllocationStack::default()),
            stacks: Mutex::new(EngineStacks::new(config)),
        }
    }

    /// Returns a shared reference to the [`Config`] of the [`EngineInner`].
    fn config(&self) -> &Config {
        &self.config
    }

    /// Allocates a new function type to the [`EngineInner`].
    fn alloc_func_type(&self, func_type: FuncType) -> DedupFuncType {
        self.res.write().func_types.alloc_func_type(func_type)
    }

    /// Resolves a deduplicated function type into a [`FuncType`] entity.
    ///
    /// # Panics
    ///
    /// - If the deduplicated function type is not owned by the engine.
    /// - If the deduplicated function type cannot be resolved to its entity.
    fn resolve_func_type<F, R>(&self, func_type: &DedupFuncType, f: F) -> R
    where
        F: FnOnce(&FuncType) -> R,
    {
        f(self.res.read().func_types.resolve_func_type(func_type))
    }

    /// Allocates a new uninitialized [`CompiledFunc`] to the [`EngineInner`].
    ///
    /// Returns a [`CompiledFunc`] reference to allow accessing the allocated [`CompiledFunc`].
    fn alloc_func(&self) -> CompiledFunc {
        self.res.write().code_map.alloc_func()
    }

    /// Returns reusable [`FuncTranslatorAllocations`] from the [`Engine`].
    fn get_translation_allocs(&self) -> FuncTranslatorAllocations {
        self.allocs.lock().get_translation_allocs()
    }

    /// Returns reusable [`FuncValidatorAllocations`] from the [`Engine`].
    fn get_validation_allocs(&self) -> FuncValidatorAllocations {
        self.allocs.lock().get_validation_allocs()
    }

    /// Returns reusable [`FuncTranslatorAllocations`] and [`FuncValidatorAllocations`] from the [`Engine`].
    ///
    /// # Note
    ///
    /// This method is a bit more efficient than calling both
    /// - [`EngineInner::get_translation_allocs`]
    /// - [`EngineInner::get_validation_allocs`]
    fn get_allocs(&self) -> (FuncTranslatorAllocations, FuncValidatorAllocations) {
        let mut allocs = self.allocs.lock();
        let translation = allocs.get_translation_allocs();
        let validation = allocs.get_validation_allocs();
        (translation, validation)
    }

    /// Recycles the given [`FuncTranslatorAllocations`] in the [`Engine`].
    fn recycle_translation_allocs(&self, allocs: FuncTranslatorAllocations) {
        self.allocs.lock().recycle_translation_allocs(allocs)
    }

    /// Recycles the given [`FuncValidatorAllocations`] in the [`Engine`].
    fn recycle_validation_allocs(&self, allocs: FuncValidatorAllocations) {
        self.allocs.lock().recycle_validation_allocs(allocs)
    }

    /// Recycles the given [`FuncTranslatorAllocations`] and [`FuncValidatorAllocations`] in the [`Engine`].
    ///
    /// # Note
    ///
    /// This method is a bit more efficient than calling both
    /// - [`EngineInner::recycle_translation_allocs`]
    /// - [`EngineInner::recycle_validation_allocs`]
    fn recycle_allocs(
        &self,
        translation: FuncTranslatorAllocations,
        validation: FuncValidatorAllocations,
    ) {
        let mut allocs = self.allocs.lock();
        allocs.recycle_translation_allocs(translation);
        allocs.recycle_validation_allocs(validation);
    }

    /// Initializes the uninitialized [`CompiledFunc`] for the [`EngineInner`].
    ///
    /// # Note
    ///
    /// The initialized function will be compiled and ready to be executed after this call.
    ///
    /// # Panics
    ///
    /// - If `func` is an invalid [`CompiledFunc`] reference for this [`CodeMap`].
    /// - If `func` refers to an already initialized [`CompiledFunc`].
    fn init_func(&self, compiled_func: CompiledFunc, func_entity: CompiledFuncEntity) {
        self.res
            .write()
            .code_map
            .init_func(compiled_func, func_entity)
    }

    /// Initializes the uninitialized [`CompiledFunc`] for the [`Engine`].
    ///
    /// # Note
    ///
    /// The initialized function will not be compiled after this call and instead
    /// be prepared to be compiled on the fly when it is called the first time.
    ///
    /// # Panics
    ///
    /// - If `func` is an invalid [`CompiledFunc`] reference for this [`CodeMap`].
    /// - If `func` refers to an already initialized [`CompiledFunc`].
    fn init_lazy_func(
        &self,
        func_idx: FuncIdx,
        func: CompiledFunc,
        bytes: &[u8],
        module: &ModuleHeader,
        func_to_validate: Option<FuncToValidate<ValidatorResources>>,
    ) {
        self.res
            .write()
            .code_map
            .init_lazy_func(func, func_idx, bytes, module, func_to_validate)
    }

    /// Resolves the [`InternalFuncEntity`] for [`CompiledFunc`] and applies `f` to it.
    ///
    /// # Panics
    ///
    /// If [`CompiledFunc`] is invalid for [`Engine`].
    #[cfg(test)]
    pub(super) fn resolve_func<F, R>(&self, func: CompiledFunc, f: F) -> Result<R, Error>
    where
        F: FnOnce(&CompiledFuncEntity) -> R,
    {
        // Note: We use `None` so this test-only function will never charge for compilation fuel.
        Ok(f(self.res.read().code_map.get(None, func)?))
    }

    /// Returns the [`Instruction`] of `func` at `index`.
    ///
    /// Returns `None` if the function has no instruction at `index`.
    ///
    /// # Errors
    ///
    /// If the `func` fails Wasm to Wasmi bytecode translation after it was lazily initialized.
    ///
    /// # Pancis
    ///
    /// If `func` cannot be resolved to a function for the [`EngineInner`].
    #[cfg(test)]
    pub(crate) fn resolve_instr(
        &self,
        func: CompiledFunc,
        index: usize,
    ) -> Result<Option<Instruction>, Error> {
        self.resolve_func(func, |func| func.instrs().get(index).copied())
    }

    /// Returns the function local constant value of `func` at `index`.
    ///
    /// Returns `None` if the function has no function local constant at `index`.
    ///
    /// # Errors
    ///
    /// If the `func` fails Wasm to Wasmi bytecode translation after it was lazily initialized.
    ///
    /// # Pancis
    ///
    /// If `func` cannot be resolved to a function for the [`EngineInner`].
    #[cfg(test)]
    fn get_func_const(
        &self,
        func: CompiledFunc,
        index: usize,
    ) -> Result<Option<UntypedVal>, Error> {
        // Function local constants are stored in reverse order of their indices since
        // they are allocated in reverse order to their absolute indices during function
        // translation. That is why we need to access them in reverse order.
        self.resolve_func(func, |func| func.consts().iter().rev().nth(index).copied())
    }

    /// Recycles the given [`Stack`].
    fn recycle_stack(&self, stack: Stack) {
        self.stacks.lock().recycle(stack)
    }
}

/// Engine resources that are immutable during function execution.
///
/// Can be shared by multiple engine executors.
#[derive(Debug)]
pub struct EngineResources {
    /// Stores information about all compiled functions.
    code_map: CodeMap,
    /// Deduplicated function types.
    ///
    /// # Note
    ///
    /// The engine deduplicates function types to make the equality
    /// comparison very fast. This helps to speed up indirect calls.
    func_types: FuncTypeRegistry,
}

impl EngineResources {
    /// Creates a new [`EngineResources`].
    fn new(config: &Config) -> Self {
        let engine_idx = EngineIdx::new();
        Self {
            code_map: CodeMap::new(config),
            func_types: FuncTypeRegistry::new(engine_idx),
        }
    }
}