wasmer_vm/
sig_registry.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4//! Implement a registry of function signatures, for fast indirect call
5//! signature checking.
6
7use crate::vmcontext::VMSharedSignatureIndex;
8use more_asserts::{assert_lt, debug_assert_lt};
9use std::collections::{hash_map, HashMap};
10use std::convert::TryFrom;
11use std::sync::RwLock;
12use wasmer_types::FunctionType;
13
14/// WebAssembly requires that the caller and callee signatures in an indirect
15/// call must match. To implement this efficiently, keep a registry of all
16/// signatures, shared by all instances, so that call sites can just do an
17/// index comparison.
18#[derive(Debug, Default)]
19pub struct SignatureRegistry {
20    // This structure is stored in an `Engine` and is intended to be shared
21    // across many instances. Ideally instances can themselves be sent across
22    // threads, and ideally we can compile across many threads. As a result we
23    // use interior mutability here with a lock to avoid having callers to
24    // externally synchronize calls to compilation.
25    inner: RwLock<Inner>,
26}
27
28#[derive(Debug, Default)]
29struct Inner {
30    signature2index: HashMap<FunctionType, VMSharedSignatureIndex>,
31    index2signature: HashMap<VMSharedSignatureIndex, FunctionType>,
32}
33
34impl SignatureRegistry {
35    /// Create a new `SignatureRegistry`.
36    pub fn new() -> Self {
37        Default::default()
38    }
39
40    /// Register a signature and return its unique index.
41    pub fn register(&self, sig: &FunctionType) -> VMSharedSignatureIndex {
42        let mut inner = self.inner.write().unwrap();
43        let len = inner.signature2index.len();
44        let entry = inner.signature2index.entry(sig.clone());
45        match entry {
46            hash_map::Entry::Occupied(entry) => *entry.get(),
47            hash_map::Entry::Vacant(entry) => {
48                // Keep `signature_hash` len under 2**32 -- VMSharedSignatureIndex::new(u32::MAX)
49                // is reserved for VMSharedSignatureIndex::default().
50                debug_assert_lt!(
51                    len,
52                    u32::MAX as usize,
53                    "Invariant check: signature_hash.len() < u32::MAX"
54                );
55                let sig_id = VMSharedSignatureIndex::new(u32::try_from(len).unwrap());
56                entry.insert(sig_id);
57                inner.index2signature.insert(sig_id, sig.clone());
58                sig_id
59            }
60        }
61    }
62
63    /// Looks up a shared signature index within this registry.
64    ///
65    /// Note that for this operation to be semantically correct the `idx` must
66    /// have previously come from a call to `register` of this same object.
67    pub fn lookup(&self, idx: VMSharedSignatureIndex) -> Option<FunctionType> {
68        self.inner
69            .read()
70            .unwrap()
71            .index2signature
72            .get(&idx)
73            .cloned()
74    }
75}