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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use std::{fmt::Display, u128};

use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;

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

/// 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(&mut self, namespace: &str) {
        unsafe { host_api::process::allow_namespace(self.id, namespace.as_ptr(), namespace.len()) };
    }

    /// Grant access to the given host directory.
    /// Returns error if host does not have access to directory.
    pub fn preopen_dir(&mut self, dir: &str) -> Result<(), LunaticError> {
        let mut error_id = 0;
        let result = unsafe {
            host_api::process::preopen_dir(
                self.id,
                dir.as_ptr(),
                dir.len(),
                &mut error_id as *mut u64,
            )
        };
        if result == 0 {
            Ok(())
        } else {
            Err(LunaticError::from(error_id))
        }
    }

    /// Add a WebAssembly module as a plugin to this configuration.
    pub fn add_plugin(&mut 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))
        }
    }
}

#[derive(Error, Debug)]
pub enum RegistryError {
    IncorrectSemver,
    IncorrectQuery,
    NotFound,
}

impl Display for RegistryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// 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 {
    pub(crate) fn from(id: u64) -> Self {
        Environment { id }
    }

    /// Create a new environment from a configuration
    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))
        }
    }

    /// Create a new environment on a remote node
    pub fn new_remote(node_name: &str, config: Config) -> Result<Self, LunaticError> {
        let mut env_or_error_id = 0;
        let result = unsafe {
            host_api::process::create_remote_environment(
                config.id,
                node_name.as_ptr(),
                node_name.len(),
                &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(&mut 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(&mut 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))
        }
    }

    /// Register a process under a specific name & version in the environment.
    ///
    /// The version must be in a correct semver format. If a process was registered under the same
    /// name and exactly same version, it will be overwritten.
    pub fn register<T: Serialize + DeserializeOwned>(
        &self,
        name: &str,
        version: &str,
        process: Process<T>,
    ) -> Result<(), RegistryError> {
        match unsafe {
            host_api::process::register(
                name.as_ptr(),
                name.len(),
                version.as_ptr(),
                version.len(),
                self.id,
                process.id,
            )
        } {
            0 => Ok(()),
            1 => Err(RegistryError::IncorrectSemver),
            _ => unreachable!(),
        }
    }

    /// Unregister a process from the environment
    pub fn unregister<T: Serialize + DeserializeOwned>(
        &self,
        name: &str,
        version: &str,
    ) -> Result<(), RegistryError> {
        match unsafe {
            host_api::process::unregister(
                name.as_ptr(),
                name.len(),
                version.as_ptr(),
                version.len(),
                self.id,
            )
        } {
            0 => Ok(()),
            1 => Err(RegistryError::IncorrectSemver),
            2 => Err(RegistryError::NotFound),
            _ => unreachable!(),
        }
    }
}

/// Returns a process that was registered inside the environment that the caller belongs to.
///
/// The query can be be an exact version or follow semver query rules (e.g. "^1.1").
pub fn lookup<T: Serialize + DeserializeOwned>(
    name: &str,
    query: &str,
) -> Result<Option<Process<T>>, RegistryError> {
    let mut process_id: u64 = 0;
    match unsafe {
        host_api::process::lookup(
            name.as_ptr(),
            name.len(),
            query.as_ptr(),
            query.len(),
            &mut process_id as *mut u64,
        )
    } {
        0 => Ok(Some(Process::from(process_id))),
        1 => Err(RegistryError::IncorrectSemver),
        2 => Ok(None),
        _ => unreachable!(),
    }
}

/// 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: Serialize + DeserializeOwned>(
        &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: Serialize + DeserializeOwned,
        P: Serialize + DeserializeOwned,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.catch_link_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: Serialize + DeserializeOwned>(
        &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), None, 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>, Tag, LinkMailbox<P>), LunaticError>
    where
        T: Serialize + DeserializeOwned,
        P: Serialize + DeserializeOwned,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.catch_link_panic();
        let tag = Tag::new();
        let proc = spawn_(
            Some(self.id),
            Some(tag),
            Context::<(), _>::Without(function),
        )?;
        Ok((proc, tag, 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: Serialize + DeserializeOwned,
        P: Serialize + DeserializeOwned,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.panic_if_link_panics();
        let proc = spawn_(
            Some(self.id),
            Some(Tag::new()),
            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 [`Serialize + DeserializeOwned`] 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: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned>(
        &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), None, 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 [`Serialize + DeserializeOwned`] 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>, Tag, LinkMailbox<P>), LunaticError>
    where
        C: Serialize + DeserializeOwned,
        T: Serialize + DeserializeOwned,
        P: Serialize + DeserializeOwned,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.catch_link_panic();
        let tag = Tag::new();
        let proc = spawn_(Some(self.id), Some(tag), Context::With(function, context))?;
        Ok((proc, tag, 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 [`Serialize + DeserializeOwned`] 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: Serialize + DeserializeOwned,
        T: Serialize + DeserializeOwned,
        P: Serialize + DeserializeOwned,
        M: TransformMailbox<P>,
    {
        let mailbox = mailbox.panic_if_link_panics();
        let proc = spawn_(
            Some(self.id),
            Some(Tag::new()),
            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
}