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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Instantiate a module, call functions, and read exports.

use crate::deprecated::{
    export::{wasmer_exports_t, wasmer_import_export_kind, NamedExport, NamedExports},
    get_global_store,
    import::{wasmer_import_t, FunctionWrapper},
    memory::wasmer_memory_t,
    value::{wasmer_value, wasmer_value_t, wasmer_value_tag},
    wasmer_result_t,
};
use crate::error::{update_last_error, CApiError};
use libc::{c_char, c_int, c_void};
use std::collections::HashMap;
use std::ffi::CStr;
use std::ptr::NonNull;
use std::slice;
use wasmer::{
    Exports, Extern, Function, Global, ImportObject, Instance, Memory, Module, Table, Val,
};
use wasmer_types::{entity::*, ExportIndex, MemoryIndex};

/// Opaque pointer to an Instance type plus metadata.
///
/// This type represents a WebAssembly instance. It
/// is generally generated by the `wasmer_instantiate()` function, or by
/// the `wasmer_module_instantiate()` function for the most common paths.
#[repr(C)]
pub struct wasmer_instance_t;

/// A wrapper around a Wasmer instance with extra data to maintain the existing API
pub(crate) struct CAPIInstance {
    /// The real wasmer `Instance`
    pub(crate) instance: Instance,
    /// List of pointers of memories that are imported into this Instance. This is
    /// required because the old Wasmer API allowed accessing these from the Instance
    /// but the new/current API does not. So we store them here to allow functions to
    /// access this data for backwards compatibilty.
    pub(crate) imported_memories: Vec<*mut Memory>,
    /// The Instance/Ctx wide data.  Previously the Ctx Instance were separate, but
    /// given the internal API changes this is no longer true: this is a single global
    /// void pointer like the old Wasmer API used to have.
    pub(crate) ctx_data: Option<NonNull<c_void>>,
}

/// Opaque pointer to a `wasmer_vm::Ctx` value in Rust.
///
/// An instance context is passed to any host function (aka imported
/// function) as the first argument. It is necessary to read the
/// instance data or the memory, respectively with the
/// `wasmer_instance_context_data_get()` function, and the
/// `wasmer_instance_context_memory()` function.
///
/// It is also possible to get the instance context outside a host
/// function by using the `wasmer_instance_context_get()`
/// function. See also `wasmer_instance_context_data_set()` to set the
/// instance context data.
///
/// Example:
///
/// ```c
/// // A host function that prints data from the WebAssembly memory to
/// // the standard output.
/// void print(wasmer_instance_context_t *context, int32_t pointer, int32_t length) {
///     // Use `wasmer_instance_context` to get back the first instance memory.
///     const wasmer_memory_t *memory = wasmer_instance_context_memory(context, 0);
///
///     // Continue…
/// }
/// ```
#[repr(C)]
pub struct wasmer_instance_context_t;

/// Creates a new WebAssembly instance from the given bytes and imports.
///
/// The result is stored in the first argument `instance` if
/// successful, i.e. when the function returns
/// `wasmer_result_t::WASMER_OK`. Otherwise
/// `wasmer_result_t::WASMER_ERROR` is returned, and
/// `wasmer_last_error_length()` with `wasmer_last_error_message()` must
/// be used to read the error message.
///
/// The caller is responsible to free the instance with
/// `wasmer_instance_destroy()`.
///
/// Example:
///
/// ```c
/// // 1. Read a WebAssembly module from a file.
/// FILE *file = fopen("sum.wasm", "r");
/// fseek(file, 0, SEEK_END);
/// long bytes_length = ftell(file);
/// uint8_t *bytes = malloc(bytes_length);
/// fseek(file, 0, SEEK_SET);
/// fread(bytes, 1, bytes_length, file);
/// fclose(file);
///
/// // 2. Declare the imports (here, none).
/// wasmer_import_t imports[] = {};
///
/// // 3. Instantiate the WebAssembly module.
/// wasmer_instance_t *instance = NULL;
/// wasmer_result_t result = wasmer_instantiate(&instance, bytes, bytes_length, imports, 0);
///
/// // 4. Check for errors.
/// if (result != WASMER_OK) {
///     int error_length = wasmer_last_error_length();
///     char *error = malloc(error_length);
///     wasmer_last_error_message(error, error_length);
///     // Do something with `error`…
/// }
///
/// // 5. Free the memory!
/// wasmer_instance_destroy(instance);
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instantiate(
    instance: *mut *mut wasmer_instance_t,
    wasm_bytes: Option<NonNull<u8>>,
    wasm_bytes_len: u32,
    imports: *mut wasmer_import_t,
    imports_len: c_int,
) -> wasmer_result_t {
    let wasm_bytes = if let Some(wasm_bytes_inner) = wasm_bytes {
        wasm_bytes_inner
    } else {
        update_last_error(CApiError {
            msg: "wasm bytes ptr is null".to_string(),
        });
        return wasmer_result_t::WASMER_ERROR;
    };

    if imports_len > 0 && imports.is_null() {
        update_last_error(CApiError {
            msg: "imports ptr is null".to_string(),
        });
        return wasmer_result_t::WASMER_ERROR;
    }

    let mut imported_memories = vec![];
    let mut instance_pointers_to_update = vec![];
    let imports: &[wasmer_import_t] = if imports_len == 0 {
        &[]
    } else {
        slice::from_raw_parts(imports, imports_len as usize)
    };

    let mut import_object = ImportObject::new();
    let mut namespaces = HashMap::new();
    for import in imports {
        let module_name = slice::from_raw_parts(
            import.module_name.bytes,
            import.module_name.bytes_len as usize,
        );
        let module_name = if let Ok(s) = std::str::from_utf8(module_name) {
            s
        } else {
            update_last_error(CApiError {
                msg: "error converting module name to string".to_string(),
            });
            return wasmer_result_t::WASMER_ERROR;
        };
        let import_name = slice::from_raw_parts(
            import.import_name.bytes,
            import.import_name.bytes_len as usize,
        );
        let import_name = if let Ok(s) = std::str::from_utf8(import_name) {
            s
        } else {
            update_last_error(CApiError {
                msg: "error converting import_name to string".to_string(),
            });
            return wasmer_result_t::WASMER_ERROR;
        };

        let namespace = namespaces.entry(module_name).or_insert_with(Exports::new);

        // TODO check that tag is actually in bounds here
        let export = match import.tag {
            wasmer_import_export_kind::WASM_MEMORY => {
                let mem = import.value.memory as *mut Memory;
                // TODO: review ownership here, probably need to clone Memory for imported_meomries
                imported_memories.push(mem);
                Extern::Memory((&*mem).clone())
            }
            wasmer_import_export_kind::WASM_FUNCTION => {
                let func_wrapper = import.value.func as *mut FunctionWrapper;
                let func_export = (*func_wrapper).func.as_ptr();
                instance_pointers_to_update.push((*func_wrapper).legacy_env.clone());
                Extern::Function((&*func_export).clone())
            }
            wasmer_import_export_kind::WASM_GLOBAL => {
                let global = import.value.global as *mut Global;
                Extern::Global((&*global).clone())
            }
            wasmer_import_export_kind::WASM_TABLE => {
                let table = import.value.table as *mut Table;
                Extern::Table((&*table).clone())
            }
        };
        namespace.insert(import_name, export);
    }
    for (module_name, namespace) in namespaces.into_iter() {
        import_object.register(module_name, namespace);
    }

    let bytes: &[u8] = slice::from_raw_parts_mut(wasm_bytes.as_ptr(), wasm_bytes_len as usize);
    let store = get_global_store();

    let module_result = Module::from_binary(store, bytes);
    let module = match module_result {
        Ok(module) => module,
        Err(error) => {
            update_last_error(error);
            return wasmer_result_t::WASMER_ERROR;
        }
    };
    let result = Instance::new(&module, &import_object);
    let new_instance = match result {
        Ok(instance) => instance,
        Err(error) => {
            update_last_error(error);
            return wasmer_result_t::WASMER_ERROR;
        }
    };
    let c_api_instance = CAPIInstance {
        instance: new_instance,
        imported_memories,
        ctx_data: None,
    };
    let c_api_instance_pointer = Box::into_raw(Box::new(c_api_instance));
    for to_update in instance_pointers_to_update {
        let mut to_update_guard = to_update.lock().unwrap();
        to_update_guard.instance_ptr = Some(NonNull::new_unchecked(c_api_instance_pointer));
    }
    *instance = c_api_instance_pointer as *mut wasmer_instance_t;
    wasmer_result_t::WASMER_OK
}

/// Returns the instance context. Learn more by looking at the
/// `wasmer_instance_context_t` struct.
///
/// This function returns `null` if `instance` is a null pointer.
///
/// Example:
///
/// ```c
/// const wasmer_instance_context_get *context = wasmer_instance_context_get(instance);
/// my_data *data = (my_data *) wasmer_instance_context_data_get(context);
/// // Do something with `my_data`.
/// ```
///
/// It is often useful with `wasmer_instance_context_data_set()`.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_context_get(
    instance: Option<NonNull<wasmer_instance_t>>,
) -> Option<&'static wasmer_instance_context_t> {
    // TODO: double check that `wasmer_instance_t` can be safely cast into CAPIInstance
    let instance: *mut CAPIInstance = instance?.cast::<CAPIInstance>().as_ptr();

    Some(&*(instance as *const wasmer_instance_context_t))
}

/// Calls an exported function of a WebAssembly instance by `name`
/// with the provided parameters. The exported function results are
/// stored on the provided `results` pointer.
///
/// This function returns `wasmer_result_t::WASMER_OK` upon success,
/// `wasmer_result_t::WASMER_ERROR` otherwise. You can use
/// `wasmer_last_error_message()` to get the generated error message.
///
/// Potential errors are the following:
///
///   * `instance` is a null pointer,
///   * `name` is a null pointer,
///   * `params` is a null pointer.
///
/// Example of calling an exported function that needs two parameters, and returns one value:
///
/// ```c
/// // First argument.
/// wasmer_value_t argument_one = {
///     .tag = WASM_I32,
///     .value.I32 = 3,
/// };
///
/// // Second argument.
/// wasmer_value_t argument_two = {
///     .tag = WASM_I32,
///     .value.I32 = 4,
/// };
///
/// // First result.
/// wasmer_value_t result_one;
///
/// // All arguments and results.
/// wasmer_value_t arguments[] = {argument_one, argument_two};
/// wasmer_value_t results[]   = {result_one};
///
/// wasmer_result_t call_result = wasmer_instance_call(
///     instance,  // instance pointer
///     "sum",     // the exported function name
///     arguments, // the arguments
///     2,         // the number of arguments
///     results,   // the results
///     1          // the number of results
/// );
///
/// if (call_result == WASMER_OK) {
///     printf("Result is: %d\n", results[0].value.I32);
/// }
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_call(
    instance: *mut wasmer_instance_t,
    name: *const c_char,
    params: *const wasmer_value_t,
    params_len: u32,
    results: *mut wasmer_value_t,
    results_len: u32,
) -> wasmer_result_t {
    if instance.is_null() {
        update_last_error(CApiError {
            msg: "instance ptr is null".to_string(),
        });

        return wasmer_result_t::WASMER_ERROR;
    }

    if name.is_null() {
        update_last_error(CApiError {
            msg: "name ptr is null".to_string(),
        });

        return wasmer_result_t::WASMER_ERROR;
    }

    if params_len > 0 && params.is_null() {
        update_last_error(CApiError {
            msg: "params ptr is null".to_string(),
        });

        return wasmer_result_t::WASMER_ERROR;
    }

    let params: Vec<Val> = {
        if params_len == 0 {
            vec![]
        } else {
            slice::from_raw_parts::<wasmer_value_t>(params, params_len as usize)
                .iter()
                .cloned()
                .map(|x| x.into())
                .collect()
        }
    };

    let function_name_c = CStr::from_ptr(name);
    let function_name_r = function_name_c.to_str().unwrap();

    let results: &mut [wasmer_value_t] = slice::from_raw_parts_mut(results, results_len as usize);

    let instance = &*(instance as *mut CAPIInstance);
    let f: &Function = match instance.instance.exports.get(function_name_r) {
        Ok(f) => f,
        Err(err) => {
            update_last_error(err);
            return wasmer_result_t::WASMER_ERROR;
        }
    };

    let result = f.call(&params[..]);

    match result {
        Ok(results_vec) => {
            if !results_vec.is_empty() {
                let ret = match results_vec[0] {
                    Val::I32(x) => wasmer_value_t {
                        tag: wasmer_value_tag::WASM_I32,
                        value: wasmer_value { I32: x },
                    },
                    Val::I64(x) => wasmer_value_t {
                        tag: wasmer_value_tag::WASM_I64,
                        value: wasmer_value { I64: x },
                    },
                    Val::F32(x) => wasmer_value_t {
                        tag: wasmer_value_tag::WASM_F32,
                        value: wasmer_value { F32: x },
                    },
                    Val::F64(x) => wasmer_value_t {
                        tag: wasmer_value_tag::WASM_F64,
                        value: wasmer_value { F64: x },
                    },
                    Val::V128(_) => unimplemented!("calling function with V128 parameter"),
                    Val::ExternRef(_) => unimplemented!("returning ExternRef type"),
                    Val::FuncRef(_) => unimplemented!("returning FuncRef type"),
                };
                results[0] = ret;
            }
            wasmer_result_t::WASMER_OK
        }
        Err(err) => {
            update_last_error(err);
            wasmer_result_t::WASMER_ERROR
        }
    }
}

/// Gets all the exports of the given WebAssembly instance.
///

/// This function stores a Rust vector of exports into `exports` as an
/// opaque pointer of kind `wasmer_exports_t`.
///
/// As is, you can do anything with `exports` except using the
/// companion functions, like `wasmer_exports_len()`,
/// `wasmer_exports_get()` or `wasmer_export_kind()`. See the example below.
///
/// **Warning**: The caller owns the object and should call
/// `wasmer_exports_destroy()` to free it.
///
/// Example:
///
/// ```c
/// // Get the exports.
/// wasmer_exports_t *exports = NULL;
/// wasmer_instance_exports(instance, &exports);
///
/// // Get the number of exports.
/// int exports_length = wasmer_exports_len(exports);
/// printf("Number of exports: %d\n", exports_length);
///
/// // Read the first export.
/// wasmer_export_t *export = wasmer_exports_get(exports, 0);
///
/// // Get the kind of the export.
/// wasmer_import_export_kind export_kind = wasmer_export_kind(export);
///
/// // Assert it is a function (why not).
/// assert(export_kind == WASM_FUNCTION);
///
/// // Read the export name.
/// wasmer_byte_array name_bytes = wasmer_export_name(export);
///
/// assert(name_bytes.bytes_len == sizeof("sum") - 1);
/// assert(memcmp(name_bytes.bytes, "sum", sizeof("sum") - 1) == 0);
///
/// // Destroy the exports.
/// wasmer_exports_destroy(exports);
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_exports(
    instance: Option<NonNull<wasmer_instance_t>>,
    exports: *mut *mut wasmer_exports_t,
) {
    let instance = if let Some(instance) = instance {
        instance.cast::<CAPIInstance>()
    } else {
        return;
    };

    let mut instance_ref_copy = instance.clone();
    let instance_ref = instance_ref_copy.as_mut();

    let exports_vec: Vec<NamedExport> = instance_ref
        .instance
        .module()
        .exports()
        .map(|export_type| NamedExport {
            export_type,
            instance,
        })
        .collect();

    let named_exports: Box<NamedExports> = Box::new(NamedExports(exports_vec));

    *exports = Box::into_raw(named_exports) as *mut wasmer_exports_t;
}

/// Sets the data that can be hold by an instance context.
///
/// An instance context (represented by the opaque
/// `wasmer_instance_context_t` structure) can hold user-defined
/// data. This function sets the data. This function is complementary
/// of `wasmer_instance_context_data_get()`.
///
/// This function does nothing if `instance` is a null pointer.
///
/// Example:
///
/// ```c
/// // Define your own data.
/// typedef struct {
///     // …
/// } my_data;
///
/// // Allocate them and set them on the given instance.
/// my_data *data = malloc(sizeof(my_data));
/// data->… = …;
/// wasmer_instance_context_data_set(instance, (void*) data);
///
/// // You can read your data.
/// {
///     my_data *data = (my_data*) wasmer_instance_context_data_get(wasmer_instance_context_get(instance));
///     // …
/// }
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_context_data_set(
    instance: Option<NonNull<wasmer_instance_t>>,
    data_ptr: *mut c_void,
) {
    let instance = if let Some(instance_inner) = instance {
        instance_inner
    } else {
        return;
    };

    instance.cast::<CAPIInstance>().as_mut().ctx_data = NonNull::new(data_ptr);
}

/// Gets the `memory_idx`th memory of the instance.
///
/// Note that the index is always `0` until multiple memories are supported.
///
/// This function is mostly used inside host functions (aka imported
/// functions) to read the instance memory.
///
/// Example of a _host function_ that reads and prints a string based on a pointer and a length:
///
/// ```c
/// void print_string(const wasmer_instance_context_t *context, int32_t pointer, int32_t length) {
///     // Get the 0th memory.
///     const wasmer_memory_t *memory = wasmer_instance_context_memory(context, 0);
///
///     // Get the memory data as a pointer.
///     uint8_t *memory_bytes = wasmer_memory_data(memory);
///
///     // Print what we assumed to be a string!
///     printf("%.*s", length, memory_bytes + pointer);
/// }
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_context_memory(
    ctx: *const wasmer_instance_context_t,
    _memory_idx: u32,
) -> Option<&'static wasmer_memory_t> {
    let instance = &*(ctx as *const CAPIInstance);
    let module = instance.instance.module();
    let memory_index = MemoryIndex::new(0);
    if module.info().is_imported_memory(memory_index) {
        if let Some(memory) = instance.imported_memories.first() {
            let memory: &Memory = &**memory;
            return Some(&*(Box::into_raw(Box::new(memory.clone())) as *const wasmer_memory_t));
        } else {
            update_last_error(CApiError {
                msg:
                    "Internal error: memory is imported but the list of imported memories is empty"
                        .to_string(),
            });
            return None;
        }
    } else {
        let exported_memory_name = if let Some(name) = module
            .info()
            .exports
            .iter()
            .filter_map(|(name, export_index)| match export_index {
                ExportIndex::Memory(idx) if *idx == memory_index => Some(name),
                _ => None,
            })
            .next()
        {
            name
        } else {
            update_last_error(CApiError {
                msg: "Could not find an exported memory".to_string(),
            });
            return None;
        };
        let memory = instance
            .instance
            .exports
            .get_memory(exported_memory_name)
            .expect(&format!(
                "Module exports memory named `{}` but it's inaccessible",
                &exported_memory_name
            ));
        Some(&*(Box::into_raw(Box::new(memory.clone())) as *const wasmer_memory_t))
    }
}

/// Gets the data that can be hold by an instance.
///
/// This function is complementary of
/// `wasmer_instance_context_data_set()`. Please read its
/// documentation. You can also read the documentation of
/// `wasmer_instance_context_t` to get other examples.
///
/// This function returns nothing if `ctx` is a null pointer.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_context_data_get(
    ctx: Option<&'static wasmer_instance_context_t>,
) -> Option<NonNull<c_void>> {
    let instance: &'static CAPIInstance = &*(ctx? as *const _ as *const CAPIInstance);
    instance.ctx_data
}

/// Frees memory for the given `wasmer_instance_t`.
///
/// Check the `wasmer_instantiate()` function to get a complete
/// example.
///
/// If `instance` is a null pointer, this function does nothing.
///
/// Example:
///
/// ```c
/// // Get an instance.
/// wasmer_instance_t *instance = NULL;
/// wasmer_instantiate(&instance, bytes, bytes_length, imports, 0);
///
/// // Destroy the instance.
/// wasmer_instance_destroy(instance);
/// ```
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_destroy(instance: Option<NonNull<wasmer_instance_t>>) {
    if let Some(instance_inner) = instance {
        Box::from_raw(instance_inner.cast::<CAPIInstance>().as_ptr());
    }
}