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
//! The runtime table module contains data structures and functions used to create and update wasm
//! tables.
use crate::{
    error::CreationError,
    export::Export,
    import::IsExport,
    types::{ElementType, TableDescriptor},
    vm,
};
use std::{
    convert::TryFrom,
    fmt, ptr,
    sync::{Arc, Mutex},
};

mod anyfunc;

pub use self::anyfunc::Anyfunc;
pub(crate) use self::anyfunc::AnyfuncTable;
use crate::error::GrowError;

/// Error type indicating why a table access failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TableAccessError {
    /// The index wasn't valid, so no element could be accessed.
    IndexError,

    // we'll need this error when we support tables holding more types
    #[allow(dead_code)]
    /// The type of the table was incorrect, so no element could be accessed.
    TypeError,
}

/// Trait indicates types that can be stored in tables
pub trait StorableInTable: Sized {
    /// Attempt to lookup self in the given table.
    fn unwrap_self(storage: &TableStorage, index: u32) -> Result<Self, TableAccessError>;

    /// Wrap value to be stored in a table.
    fn wrap_self(self, storage: &mut TableStorage, index: u32) -> Result<(), TableAccessError>;
}

impl<'a, F: Into<Anyfunc<'a>> + TryFrom<Anyfunc<'a>>> StorableInTable for F {
    fn unwrap_self(storage: &TableStorage, index: u32) -> Result<Self, TableAccessError> {
        match storage {
            TableStorage::Anyfunc(ref anyfunc_table) => {
                let anyfunc = anyfunc_table
                    .get(index)
                    .ok_or(TableAccessError::IndexError)?;
                // Should this be a different error value because it's not a table type error?
                F::try_from(anyfunc).map_err(|_| TableAccessError::TypeError)
            }
        }
    }

    fn wrap_self(self, storage: &mut TableStorage, index: u32) -> Result<(), TableAccessError> {
        let anyfunc: Anyfunc = self.into();

        match storage {
            TableStorage::Anyfunc(ref mut anyfunc_table) => anyfunc_table
                .set(index, anyfunc)
                .map_err(|_| TableAccessError::IndexError),
        }
    }
}

/// Kind of table element.
// note to implementors: all types in `Element` should implement `StorableInTable`.
pub enum Element<'a> {
    /// Anyfunc.
    Anyfunc(Anyfunc<'a>),
}

// delegation implementation for `Element`
impl<'a> StorableInTable for Element<'a> {
    fn unwrap_self(storage: &TableStorage, index: u32) -> Result<Self, TableAccessError> {
        match storage {
            TableStorage::Anyfunc(ref anyfunc_table) => anyfunc_table
                .get(index)
                .map(Element::Anyfunc)
                .ok_or(TableAccessError::IndexError),
        }
    }

    fn wrap_self(self, storage: &mut TableStorage, index: u32) -> Result<(), TableAccessError> {
        match self {
            Element::Anyfunc(af) => af.wrap_self(storage, index),
        }
    }
}

/// Kind of table storage.
// #[derive(Debug)]
pub enum TableStorage {
    /// This is intended to be a caller-checked Anyfunc.
    Anyfunc(Box<AnyfuncTable>),
}

/// Container with a descriptor and a reference to a table storage.
pub struct Table {
    desc: TableDescriptor,
    storage: Arc<Mutex<(TableStorage, vm::LocalTable)>>,
}

impl Table {
    /// Create a new `Table` from a [`TableDescriptor`]
    ///
    /// [`TableDescriptor`]: struct.TableDescriptor.html
    ///
    /// Usage:
    ///
    /// ```
    /// # use wasmer_runtime_core::types::{TableDescriptor, ElementType};
    /// # use wasmer_runtime_core::table::Table;
    /// # use wasmer_runtime_core::error::Result;
    /// # fn create_table() -> Result<()> {
    /// let descriptor = TableDescriptor {
    ///     element: ElementType::Anyfunc,
    ///     minimum: 10,
    ///     maximum: None,
    /// };
    ///
    /// let table = Table::new(descriptor)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(desc: TableDescriptor) -> Result<Self, CreationError> {
        if let Some(max) = desc.maximum {
            if max < desc.minimum {
                return Err(CreationError::InvalidDescriptor(
                    "Max table size is less than the minimum size".to_string(),
                ));
            }
        }

        let mut local = vm::LocalTable {
            base: ptr::null_mut(),
            count: 0,
            table: ptr::null_mut(),
        };

        let storage = match desc.element {
            ElementType::Anyfunc => TableStorage::Anyfunc(AnyfuncTable::new(desc, &mut local)?),
        };

        Ok(Self {
            desc,
            storage: Arc::new(Mutex::new((storage, local))),
        })
    }

    /// Get the `TableDescriptor` used to create this `Table`.
    pub fn descriptor(&self) -> TableDescriptor {
        self.desc
    }

    // Made `pub(crate)` because this API is incomplete, see `anyfunc::AnyfuncTable::get`
    // for more information.
    #[allow(dead_code)]
    /// Get the raw table value at index. A return value of `None` means either that
    /// the index or the type wasn't valid.
    pub(crate) fn get<T: StorableInTable>(&self, index: u32) -> Result<T, TableAccessError> {
        let guard = self.storage.lock().unwrap();
        let (storage, _) = &*guard;
        T::unwrap_self(storage, index)
    }

    /// Set the element at index.
    pub fn set<T: StorableInTable>(&self, index: u32, element: T) -> Result<(), TableAccessError> {
        let mut guard = self.storage.lock().unwrap();
        let (storage, _) = &mut *guard;
        T::wrap_self(element, storage, index)
    }

    pub(crate) fn anyfunc_direct_access_mut<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut [vm::Anyfunc]) -> R,
    {
        let mut storage = self.storage.lock().unwrap();
        match &mut *storage {
            (TableStorage::Anyfunc(ref mut anyfunc_table), _) => f(anyfunc_table.internal_buffer()),
        }
    }

    /// The current size of this table.
    pub fn size(&self) -> u32 {
        let storage = self.storage.lock().unwrap();
        match &*storage {
            (TableStorage::Anyfunc(ref anyfunc_table), _) => anyfunc_table.current_size(),
        }
    }

    /// Grow this table by `delta`.
    pub fn grow(&self, delta: u32) -> Result<u32, GrowError> {
        if delta == 0 {
            return Ok(self.size());
        }

        let mut storage = self.storage.lock().unwrap();
        match &mut *storage {
            (TableStorage::Anyfunc(ref mut anyfunc_table), ref mut local) => anyfunc_table
                .grow(delta, local)
                .ok_or(GrowError::TableGrowError),
        }
    }

    /// Get a mutable pointer to underlying table storage.
    pub fn vm_local_table(&mut self) -> *mut vm::LocalTable {
        let mut storage = self.storage.lock().unwrap();
        &mut storage.1
    }
}

impl IsExport for Table {
    fn to_export(&self) -> Export {
        Export::Table(self.clone())
    }
}

impl Clone for Table {
    fn clone(&self) -> Self {
        Self {
            desc: self.desc,
            storage: Arc::clone(&self.storage),
        }
    }
}

impl fmt::Debug for Table {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Table")
            .field("desc", &self.desc)
            .field("size", &self.size())
            .finish()
    }
}

#[cfg(test)]
mod table_tests {

    use super::{ElementType, Table, TableDescriptor};

    #[test]
    fn test_initial_table_size() {
        let table = Table::new(TableDescriptor {
            element: ElementType::Anyfunc,
            minimum: 10,
            maximum: Some(20),
        })
        .unwrap();
        assert_eq!(table.size(), 10);
    }
}