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
use std::u128;

use crate::{
    error::LunaticError,
    host_api,
    mailbox::{LinkMailbox, Mailbox, TransformMailbox},
    message::Message,
    process::{spawn_, Context, Process},
};

/// Environment configuration
pub struct Config {
    id: u64,
}

impl Drop for Config {
    fn drop(&mut self) {
        unsafe { host_api::process::drop_config(self.id) };
    }
}

impl Config {
    /// Create a new configuration
    pub fn new(max_memory: u64, max_fuel: Option<u64>) -> Self {
        let max_fuel = max_fuel.unwrap_or(0);
        let id = unsafe { host_api::process::create_config(max_memory, max_fuel) };
        Self { id }
    }

    /// Allow a host function namespace to be used by processes spawned with this configuration.
    ///
    /// Namespaces can be exact function matches (e.g. `lunatic::error::string_size`) or just a
    /// prefix (e.g. `lunatic::error::`) matching all functions inside of the namespace.
    ///
    /// An empty string ("") is considered a prefix of **all** namespaces.
    pub fn allow_namespace(&self, namespace: &str) {
        unsafe { host_api::process::allow_namespace(self.id, namespace.as_ptr(), namespace.len()) };
    }

    /// Add a WebAssembly module as a plugin to this configuration.
    pub fn add_plugin(&self, plugin: &[u8]) -> Result<(), LunaticError> {
        let mut error_id = 0;
        let result = unsafe {
            host_api::process::add_plugin(
                self.id,
                plugin.as_ptr(),
                plugin.len(),
                &mut error_id as *mut u64,
            )
        };
        if result == 0 {
            Ok(())
        } else {
            Err(LunaticError::from(error_id))
        }
    }
}

/// Environments can define characteristics of processes that are spawned into it.
pub struct Environment {
    id: u64,
}

impl Drop for Environment {
    fn drop(&mut self) {
        unsafe { host_api::process::drop_environment(self.id) };
    }
}

impl Environment {
    /// Create a new environment from a configurationS
    pub fn new(config: Config) -> Result<Self, LunaticError> {
        let mut env_or_error_id = 0;
        let result = unsafe {
            host_api::process::create_environment(config.id, &mut env_or_error_id as *mut u64)
        };
        if result == 0 {
            Ok(Self {
                id: env_or_error_id,
            })
        } else {
            Err(LunaticError::from(env_or_error_id))
        }
    }

    /// Add a WebAssembly module to the environment.
    pub fn add_module(&self, module: &[u8]) -> Result<Module, LunaticError> {
        let mut module_or_error_id = 0;
        let result = unsafe {
            host_api::process::add_module(
                self.id,
                module.as_ptr(),
                module.len(),
                &mut module_or_error_id as *mut u64,
            )
        };
        if result == 0 {
            Ok(Module {
                id: module_or_error_id,
            })
        } else {
            Err(LunaticError::from(module_or_error_id))
        }
    }

    /// Add the module that is being currently executed to the environment.
    pub fn add_this_module(&self) -> Result<ThisModule, LunaticError> {
        let mut module_or_error_id = 0;
        let result = unsafe {
            host_api::process::add_this_module(self.id, &mut module_or_error_id as *mut u64)
        };
        if result == 0 {
            Ok(ThisModule {
                id: module_or_error_id,
            })
        } else {
            Err(LunaticError::from(module_or_error_id))
        }
    }
}

/// A compiled instance of a WebAssembly module.
///
/// Modules belong to [`Environments`](Environment) and processes spawned from the modules will
/// have characteristics defined by the [`Environment`].
///
/// Creating a module will also JIT compile it, this can be a compute intensive tasks.
pub struct Module {
    id: u64,
}

impl Drop for Module {
    fn drop(&mut self) {
        unsafe { host_api::process::drop_module(self.id) };
    }
}

impl Module {
    /// Spawn a new process and use `function` as the entry point. If the function takes arguments
    /// the passed in `params` need to exactly match their types.
    pub fn spawn<T: Message>(
        &self,
        function: &str,
        params: &[Param],
    ) -> Result<Process<T>, LunaticError> {
        let mut process_or_error_id = 0;
        let params: Vec<u8> = params_to_vec(params);
        let result = unsafe {
            host_api::process::spawn(
                0,
                self.id,
                function.as_ptr(),
                function.len(),
                params.as_ptr(),
                params.len(),
                &mut process_or_error_id as *mut u64,
            )
        };

        if result == 0 {
            Ok(Process::from(process_or_error_id))
        } else {
            Err(LunaticError::from(process_or_error_id))
        }
    }

    /// Spawn a new process and link it to the current one.
    pub fn spawn_link<T, P, M>(
        &self,
        mailbox: M,
        function: &str,
        params: &[Param],
    ) -> Result<(Process<T>, LinkMailbox<P>), LunaticError>
    where
        T: Message,
        P: Message,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.catch_child_panic();
        let mut process_or_error_id = 0;
        let params: Vec<u8> = params_to_vec(params);
        let result = unsafe {
            host_api::process::spawn(
                1,
                self.id,
                function.as_ptr(),
                function.len(),
                params.as_ptr(),
                params.len(),
                &mut process_or_error_id as *mut u64,
            )
        };

        if result == 0 {
            Ok((Process::from(process_or_error_id), mailbox))
        } else {
            Err(LunaticError::from(process_or_error_id))
        }
    }
}

/// A pointer to the current module.
///
/// This type is useful because it allows us to spawn existing functions by reference into a new
/// environment. This is only possible if we are running inside the module we are spawning the
/// processes from, otherwise we could not reference them by table id.
pub struct ThisModule {
    id: u64,
}

impl Drop for ThisModule {
    fn drop(&mut self) {
        unsafe { host_api::process::drop_module(self.id) };
    }
}

impl ThisModule {
    /// Spawns a new process from a function.
    ///
    /// - `function` is the starting point of the new process. The new process doesn't share
    ///   memory with its parent, because of this the function can't capture anything from parents.
    pub fn spawn<T: Message>(&self, function: fn(Mailbox<T>)) -> Result<Process<T>, LunaticError> {
        // LinkMailbox<T> & Mailbox<T> are marker types and it's safe to cast to Mailbox<T> here if we
        //  set the `link` argument to `false`.
        let function = unsafe { std::mem::transmute(function) };
        spawn_(Some(self.id), false, Context::<(), _>::Without(function))
    }

    /// Spawns a new process from a function and links it to the parent.
    ///
    /// - `function` is the starting point of the new process. The new process doesn't share
    ///   memory with its parent, because of this the function can't capture anything from parents.
    pub fn spawn_link<T, P, M>(
        &self,
        mailbox: M,
        function: fn(Mailbox<T>),
    ) -> Result<(Process<T>, LinkMailbox<P>), LunaticError>
    where
        T: Message,
        P: Message,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.catch_child_panic();
        let proc = spawn_(Some(self.id), true, Context::<(), _>::Without(function))?;
        Ok((proc, mailbox))
    }

    /// Spawns a new process from a function and links it to the parent.
    ///
    /// - `function` is the starting point of the new process. The new process doesn't share
    ///   memory with its parent, because of this the function can't capture anything from parents.
    ///
    /// If the linked process dies, the parent is going to die too.
    pub fn spawn_link_unwrap<T, P, M>(
        &self,
        mailbox: M,
        function: fn(Mailbox<T>),
    ) -> Result<(Process<T>, Mailbox<P>), LunaticError>
    where
        T: Message,
        P: Message,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.panic_if_child_panics();
        let proc = spawn_(Some(self.id), true, Context::<(), _>::Without(function))?;
        Ok((proc, mailbox))
    }

    /// Spawns a new process from a function and context.
    ///
    /// - `context` is  data that we want to pass to the newly spawned process. It needs to impl.
    ///    the [`Message`] trait.
    ///
    /// - `function` is the starting point of the new process. The new process doesn't share
    ///   memory with its parent, because of this the function can't capture anything from parents.
    ///   The first argument of this function is going to be the received `context`.
    pub fn spawn_with<C: Message, T: Message>(
        &self,
        context: C,
        function: fn(C, Mailbox<T>),
    ) -> Result<Process<T>, LunaticError> {
        // LinkMailbox<T> & Mailbox<T> are marker types and it's safe to cast to Mailbox<T> here if we
        //  set the `link` argument to `false`.
        let function = unsafe { std::mem::transmute(function) };
        spawn_(Some(self.id), false, Context::With(function, context))
    }

    /// Spawns a new process from a function and context, and links it to the parent.
    ///
    /// - `context` is  data that we want to pass to the newly spawned process. It needs to impl.
    ///    the [`Message`] trait.
    ///
    /// - `function` is the starting point of the new process. The new process doesn't share
    ///   memory with its parent, because of this the function can't capture anything from parents.
    ///   The first argument of this function is going to be the received `context`.
    pub fn spawn_link_with<C, T, P, M>(
        &self,
        mailbox: M,
        context: C,
        function: fn(C, Mailbox<T>),
    ) -> Result<(Process<T>, LinkMailbox<P>), LunaticError>
    where
        C: Message,
        T: Message,
        P: Message,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.catch_child_panic();
        let proc = spawn_(Some(self.id), true, Context::With(function, context))?;
        Ok((proc, mailbox))
    }

    /// Spawns a new process from a function and context, and links it to the parent.
    ///
    /// - `context` is  data that we want to pass to the newly spawned process. It needs to impl.
    ///    the [`Message`] trait.
    ///
    /// - `function` is the starting point of the new process. The new process doesn't share
    ///   memory with its parent, because of this the function can't capture anything from parents.
    ///   The first argument of this function is going to be the received `context`.
    ///
    /// If the linked process dies, the parent is going to die too.
    pub fn spawn_link_unwrap_with<C, T, P, M>(
        &self,
        mailbox: M,
        context: C,
        function: fn(C, Mailbox<T>),
    ) -> Result<(Process<T>, Mailbox<P>), LunaticError>
    where
        C: Message,
        T: Message,
        P: Message,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.panic_if_child_panics();
        let proc = spawn_(Some(self.id), true, Context::With(function, context))?;
        Ok((proc, mailbox))
    }
}

pub enum Param {
    I32(i32),
    I64(i64),
    V128(u128),
}

pub(crate) fn params_to_vec(params: &[Param]) -> Vec<u8> {
    let mut result = Vec::with_capacity(params.len() * 17);
    params.iter().for_each(|param| match param {
        Param::I32(value) => {
            result.push(0x7F);
            result.extend((*value as u128).to_le_bytes())
        }
        Param::I64(value) => {
            result.push(0x7E);
            result.extend((*value as u128).to_le_bytes())
        }
        Param::V128(value) => {
            result.push(0x7B);
            result.extend((*value).to_le_bytes())
        }
    });
    result
}