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
use anyhow::Result;
use byteorder::{LittleEndian, ReadBytesExt};
use jamsocket::{ClientId, JamsocketContext, JamsocketService, MessageRecipient};
use std::{borrow::BorrowMut, sync::Arc};
use wasmtime::{Caller, Engine, Extern, Instance, Linker, Memory, Module, Store, TypedFunc, Val};
use wasmtime_wasi::sync::WasiCtxBuilder;
use wasmtime_wasi::WasiCtx;

use crate::WasmRuntimeError;

const ENV: &str = "env";
const EXT_MEMORY: &str = "memory";
const EXT_FN_CONNECT: &str = "connect";
const EXT_FN_DISCONNECT: &str = "disconnect";
const EXT_FN_BINARY: &str = "binary";
const EXT_FN_MESSAGE: &str = "message";
const EXT_FN_SEND_MESSAGE: &str = "send_message";
const EXT_FN_SEND_BINARY: &str = "send_binary";
const EXT_FN_SET_TIMER: &str = "set_timer";
const EXT_FN_TIMER: &str = "timer";
const EXT_FN_INITIALIZE: &str = "initialize";
const EXT_FN_MALLOC: &str = "jam_malloc";
const EXT_FN_FREE: &str = "jam_free";
const EXT_JAMSOCKET_VERSION: &str = "JAMSOCKET_API_VERSION";
const EXT_JAMSOCKET_PROTOCOL: &str = "JAMSOCKET_API_PROTOCOL";

const EXPECTED_API_VERSION: i32 = 1;
const EXPECTED_PROTOCOL_VERSION: i32 = 0;

/// Hosts a [jamsocket::JamsocketService] implemented by a WebAssembly module.
pub struct WasmHost {
    store: Store<WasiCtx>,
    memory: Memory,

    fn_malloc: TypedFunc<u32, u32>,
    fn_free: TypedFunc<(u32, u32), ()>,
    fn_message: TypedFunc<(u32, u32, u32), ()>,
    fn_binary: TypedFunc<(u32, u32, u32), ()>,
    fn_connect: TypedFunc<u32, ()>,
    fn_disconnect: TypedFunc<u32, ()>,
    fn_timer: TypedFunc<(), ()>,
}

impl WasmHost {
    fn put_data(&mut self, data: &[u8]) -> Result<(u32, u32)> {
        #[allow(clippy::cast_possible_truncation)]
        let len = data.len() as u32;
        let pt = self.fn_malloc.call(&mut self.store, len)?;

        self.memory.write(&mut self.store, pt as usize, data)?;

        Ok((pt, len))
    }

    fn try_message(&mut self, client: ClientId, message: &str) -> Result<()> {
        let (pt, len) = self.put_data(message.as_bytes())?;

        self.fn_message
            .call(&mut self.store, (client.into(), pt, len))?;

        self.fn_free.call(&mut self.store, (pt, len))?;

        Ok(())
    }

    fn try_binary(&mut self, client: ClientId, message: &[u8]) -> Result<()> {
        let (pt, len) = self.put_data(message)?;

        self.fn_binary
            .call(&mut self.store, (client.into(), pt as u32, len))?;

        self.fn_free.call(&mut self.store, (pt, len))?;

        Ok(())
    }
}

impl JamsocketService for WasmHost {
    fn message(&mut self, client: ClientId, message: &str) {
        if let Err(error) = self.try_message(client, message) {
            tracing::error!(?error, "Error calling `message` on wasm host");
        }
    }

    fn connect(&mut self, client: ClientId) {
        if let Err(error) = self.fn_connect.call(&mut self.store, client.into()) {
            tracing::error!(?error, "Error calling `connect` on wasm host");
        }
    }

    fn disconnect(&mut self, client: ClientId) {
        if let Err(error) = self.fn_disconnect.call(&mut self.store, client.into()) {
            tracing::error!(?error, "Error calling `disconnect` on wasm host");
        };
    }

    fn timer(&mut self) {
        if let Err(error) = self.fn_timer.call(&mut self.store, ()) {
            tracing::error!(?error, "Error calling `timer` on wasm host");
        };
    }

    fn binary(&mut self, client: ClientId, message: &[u8]) {
        if let Err(error) = self.try_binary(client, message) {
            tracing::error!(?error, "Error calling `binary` on wasm host");
        };
    }
}

#[inline]
fn get_memory<T>(caller: &mut Caller<'_, T>) -> Memory {
    match caller.get_export(EXT_MEMORY) {
        Some(Extern::Memory(mem)) => mem,
        _ => panic!(),
    }
}

#[inline]
fn get_string<'a, T>(
    caller: &'a Caller<'_, T>,
    memory: &'a Memory,
    start: u32,
    len: u32,
) -> Result<&'a str> {
    let data = get_u8_vec(caller, memory, start, len);
    std::str::from_utf8(data).map_err(|e| e.into())
}

#[inline]
fn get_u8_vec<'a, T>(
    caller: &'a Caller<'_, T>,
    memory: &'a Memory,
    start: u32,
    len: u32,
) -> &'a [u8] {
    let data = memory
        .data(caller)
        .get(start as usize..(start + len) as usize);
    match data {
        Some(data) => data,
        None => panic!(),
    }
}

pub fn get_global<T>(
    store: &mut Store<T>,
    memory: &mut Memory,
    instance: &Instance,
    name: &str,
) -> Result<i32> {
    #[allow(clippy::cast_sign_loss)]
    let i: u32 = {
        let mem_location = instance
            .get_global(store.borrow_mut(), name)
            .ok_or(WasmRuntimeError::CouldNotImportGlobal)?;

        match mem_location.get(store.borrow_mut()) {
            Val::I32(i) => Ok(i),
            _ => Err(WasmRuntimeError::CouldNotImportGlobal),
        }? as u32
    };

    #[allow(clippy::cast_possible_truncation)]
    let mut value = memory
        .data(store)
        .get(i as usize..(i as usize + std::mem::size_of::<i32>()))
        .ok_or(WasmRuntimeError::CouldNotImportGlobal)?;
    let result = value.read_i32::<LittleEndian>()?;
    Ok(result)
}

impl WasmHost {
    pub fn new(
        room_id: &str,
        module: &Module,
        engine: &Engine,
        context: &Arc<impl JamsocketContext>,
    ) -> Result<Self> {
        let wasi = WasiCtxBuilder::new().build();

        let mut store = Store::new(engine, wasi);
        let mut linker = Linker::new(engine);
        wasmtime_wasi::add_to_linker(&mut linker, |s| s)?;

        {
            #[allow(clippy::redundant_clone)]
            let context = context.clone();
            linker.func_wrap(
                ENV,
                EXT_FN_SEND_MESSAGE,
                move |mut caller: Caller<'_, WasiCtx>, client: u32, start: u32, len: u32| {
                    let memory = get_memory(&mut caller);
                    let message = get_string(&caller, &memory, start, len)?;

                    context.send_message(MessageRecipient::decode_u32(client), message);

                    Ok(())
                },
            )?;
        }

        {
            #[allow(clippy::redundant_clone)]
            let context = context.clone();
            linker.func_wrap(
                ENV,
                EXT_FN_SEND_BINARY,
                move |mut caller: Caller<'_, WasiCtx>, client: u32, start: u32, len: u32| {
                    let memory = get_memory(&mut caller);
                    let message = get_u8_vec(&caller, &memory, start, len);

                    context.send_binary(MessageRecipient::decode_u32(client), message);

                    Ok(())
                },
            )?;
        }

        {
            #[allow(clippy::redundant_clone)]
            let context = context.clone();
            linker.func_wrap(
                ENV,
                EXT_FN_SET_TIMER,
                move |_: Caller<'_, WasiCtx>, duration_ms: u32| {
                    context.set_timer(duration_ms);

                    Ok(())
                },
            )?;
        }

        let instance = linker.instantiate(&mut store, module)?;

        let initialize =
            instance.get_typed_func::<(u32, u32), (), _>(&mut store, EXT_FN_INITIALIZE)?;

        let fn_malloc = instance.get_typed_func::<u32, u32, _>(&mut store, EXT_FN_MALLOC)?;

        let fn_free = instance.get_typed_func::<(u32, u32), (), _>(&mut store, EXT_FN_FREE)?;

        let mut memory = instance
            .get_memory(&mut store, EXT_MEMORY)
            .ok_or(WasmRuntimeError::CouldNotImportMemory)?;

        {
            let room_id = room_id.as_bytes();
            #[allow(clippy::cast_possible_truncation)]
            let len = room_id.len() as u32;
            let pt = fn_malloc.call(&mut store, len)?;

            memory.write(&mut store, pt as usize, room_id)?;
            initialize.call(&mut store, (pt, len))?;

            fn_free.call(&mut store, (pt, len))?;
        }

        if get_global(&mut store, &mut memory, &instance, EXT_JAMSOCKET_VERSION)?
            != EXPECTED_API_VERSION
        {
            return Err(WasmRuntimeError::InvalidApiVersion.into());
        }

        if get_global(&mut store, &mut memory, &instance, EXT_JAMSOCKET_PROTOCOL)?
            != EXPECTED_PROTOCOL_VERSION
        {
            return Err(WasmRuntimeError::InvalidProtocolVersion.into());
        }

        let fn_connect = instance.get_typed_func::<u32, (), _>(&mut store, EXT_FN_CONNECT)?;

        let fn_disconnect = instance.get_typed_func::<u32, (), _>(&mut store, EXT_FN_DISCONNECT)?;

        let fn_timer = instance.get_typed_func::<(), (), _>(&mut store, EXT_FN_TIMER)?;

        let fn_message =
            instance.get_typed_func::<(u32, u32, u32), (), _>(&mut store, EXT_FN_MESSAGE)?;

        let fn_binary =
            instance.get_typed_func::<(u32, u32, u32), (), _>(&mut store, EXT_FN_BINARY)?;

        Ok(WasmHost {
            store,
            memory,
            fn_malloc,
            fn_free,
            fn_message,
            fn_binary,
            fn_connect,
            fn_disconnect,
            fn_timer,
        })
    }
}