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
pub mod memory;
pub mod state;
pub mod types;
#[cfg(feature = "vm-wasmer")]
pub mod wasmer;

use std::convert::Into;
use std::fmt::Debug;
use std::{
    cell::{Ref, RefCell, RefMut},
    rc::Rc,
};

pub use smallvec::SmallVec;
pub use uptown_funk_macro::host_functions;

/// Provides access to the instance execution environment.
pub trait Executor {
    type Return: Clone;

    /// Execute `Future` f.
    #[cfg(feature = "async")]
    fn async_<R, F>(&self, f: F) -> R
    where
        F: std::future::Future<Output = R>;

    /// Get mutable access to the instance memory.
    fn memory(&self) -> memory::Memory;
}

pub trait HostFunctions: Sized {
    type Return: Clone + 'static;

    #[cfg(feature = "vm-wasmtime")]
    fn add_to_linker<E>(self, executor: E, linker: &mut wasmtime::Linker) -> Self::Return
    where
        E: Executor + Clone + 'static;

    #[cfg(feature = "vm-wasmer")]
    fn add_to_wasmer_linker<E>(
        self,
        executor: E,
        linker: &mut wasmer::WasmerLinker,
        store: &::wasmer::Store,
    ) -> Self::Return
    where
        E: Executor + Clone + 'static;
}

pub trait StateMarker: Sized {}
pub trait Convert<To: Sized>: Sized {
    fn convert(&mut self) -> &mut To;
}

impl<T: StateMarker> Convert<T> for T {
    fn convert(&mut self) -> &mut T {
        self
    }
}

impl<'a, T: StateMarker> Convert<T> for RefMut<'a, T> {
    fn convert(&mut self) -> &mut T {
        self
    }
}

static mut NOSTATE: () = ();

impl<T: StateMarker> Convert<()> for T {
    fn convert(&mut self) -> &mut () {
        unsafe { &mut NOSTATE }
    }
}

impl<'a, T: StateMarker> Convert<()> for RefMut<'a, T> {
    fn convert(&mut self) -> &mut () {
        unsafe { &mut NOSTATE }
    }
}

impl Convert<()> for () {
    fn convert(&mut self) -> &mut () {
        self
    }
}

pub trait FromWasm {
    type From;
    type State: Convert<Self::State> + Convert<()>;

    fn from(
        state: &mut Self::State,
        executor: &impl Executor,
        from: Self::From,
    ) -> Result<Self, Trap>
    where
        Self: Sized;
}

pub trait ToWasm {
    type To;
    type State: Convert<Self::State> + Convert<()>;

    fn to(
        state: &mut Self::State,
        executor: &impl Executor,
        host_value: Self,
    ) -> Result<Self::To, Trap>;
}

pub struct StateWrapper<S, E: Executor> {
    state: Rc<RefCell<S>>,
    env: Rc<E>,
}

impl<S, E: Executor> StateWrapper<S, E> {
    pub fn new(state: S, executor: E) -> Self {
        Self {
            state: Rc::new(RefCell::new(state)),
            env: Rc::new(executor),
        }
    }

    pub fn borrow_state(&self) -> Ref<S> {
        self.state.borrow()
    }

    pub fn borrow_state_mut(&self) -> RefMut<S> {
        self.state.borrow_mut()
    }

    pub fn get_state(&self) -> Rc<RefCell<S>> {
        self.state.clone()
    }

    pub fn executor(&self) -> &E {
        &self.env
    }

    pub fn memory(&self) -> memory::Memory {
        self.env.memory()
    }

    pub fn recover_state(self) -> Result<S, ()> {
        match Rc::try_unwrap(self.state) {
            Ok(s) => Ok(s.into_inner()),
            Err(_) => Err(()),
        }
    }
}

// TODO document these
#[cfg(feature = "vm-wasmer")]
unsafe impl<S, E: Executor> Send for StateWrapper<S, E> {}
#[cfg(feature = "vm-wasmer")]
unsafe impl<S, E: Executor> Sync for StateWrapper<S, E> {}

impl<S, E: Executor> Clone for StateWrapper<S, E> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            env: self.env.clone(),
        }
    }
}

#[cfg(feature = "vm-wasmer")]
impl<S, E: Executor> ::wasmer::WasmerEnv for StateWrapper<S, E> {
    fn init_with_instance(
        &mut self,
        _: &::wasmer::Instance,
    ) -> Result<(), ::wasmer::HostEnvInitError> {
        Ok(())
    }
}

#[cfg_attr(feature = "vm-wasmer", derive(thiserror::Error))]
#[cfg_attr(feature = "vm-wasmer", error("{message}"))]
pub struct Trap<D = ()>
where
    D: 'static,
{
    message: String,
    data: Option<D>,
}

impl<D> Debug for Trap<D> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.message, f)
    }
}

impl Trap<()> {
    pub fn new<I: Into<String>>(message: I) -> Self {
        Self {
            message: message.into(),
            data: None,
        }
    }

    pub fn with_data<D: 'static>(self, data: D) -> Trap<D> {
        Trap {
            message: self.message,
            data: Some(data),
        }
    }

    pub fn try_option<R: Debug>(result: Option<R>) -> Result<R, Trap> {
        match result {
            Some(r) => Ok(r),
            None => Err(Trap::new(
                "Host function trapped: Memory location not inside wasm guest",
            )),
        }
    }

    pub fn try_result<R: Debug, E: Debug>(result: Result<R, E>) -> Result<R, Trap> {
        match result {
            Ok(r) => Ok(r),
            Err(_) => {
                let message = format!("Host function trapped: {:?}", result);
                Err(Trap::new(message))
            }
        }
    }
}

impl ToWasm for Trap {
    type To = ();
    type State = ();

    fn to(_: &mut (), _: &impl Executor, v: Self) -> Result<(), Trap> {
        Err(v)
    }
}

#[cfg(feature = "vm-wasmtime")]
impl From<Trap> for wasmtime::Trap {
    fn from(trap: Trap) -> Self {
        wasmtime::Trap::new(trap.message)
    }
}

#[repr(C)]
pub struct IoVecT {
    pub ptr: u32,
    pub len: u32,
}