wasmtime-cli 46.0.2

Command-line interface for Wasmtime
Documentation
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
//! Tests that objects belonging to one `Engine` cannot be admitted into a
//! `Store` that belongs to a different `Engine`.
//!
//! Type indices (`VMSharedTypeIndex`) are unique only within a single
//! `Engine`. Two engines will happily hand out the same index for two
//! completely unrelated types. When an object from one engine reaches a store
//! from another, those numerically-equal-but-semantically-different indices
//! collide:
//!
//! * A host function's `wasm_call` field gets patched with a Wasm-to-array
//!   trampoline compiled for a different signature, so the trampoline reads
//!   and writes the wrong number of `ValRaw` slots in a stack buffer.
//!
//! * The garbage collector traces a Wasm object using a foreign type's
//!   layout.
//!
//! Every API that lets an object into a store must therefore check that the
//! object comes from the store's engine.

use crate::ErrorExt;
use std::sync::{Arc, Mutex};
use wasmtime::component::{Component, Linker as ComponentLinker};
use wasmtime::*;

/// The value that [`observe_i64_in_host`] sends from Wasm to the host.
const SENTINEL: i64 = 0x1122334455667788;

/// A module whose only function type is `(func (param f64))`.
///
/// In a freshly created engine that type gets the same `VMSharedTypeIndex` as
/// the `(func (param i64))` type used by [`observe_i64_in_host`], so if this
/// module is registered with a store belonging to a different engine then its
/// trampoline is what the host function ends up calling.
const COLLIDING_MODULE: &str = r#"(module (func (export "f") (param f64)))"#;

/// [`COLLIDING_MODULE`] wrapped up in a component.
///
/// The core module is deliberately left uninstantiated so that instantiating
/// this component does not itself instantiate any core module.
const COLLIDING_COMPONENT: &str = r#"
    (component
        (core module (func (export "f") (param f64)))
    )
"#;

/// Two separate engines that assign the same type indices to different types.
fn engine_pair() -> (Engine, Engine) {
    (Engine::default(), Engine::default())
}

/// Same as [`engine_pair`], but with a customized configuration.
fn engine_pair_with(f: impl Fn(&mut Config)) -> Result<(Engine, Engine)> {
    let mut config = Config::new();
    f(&mut config);
    Ok((Engine::new(&config)?, Engine::new(&config)?))
}

/// Calls a host function that takes an `i64` and returns the value that the
/// host actually observed, which should always be [`SENTINEL`].
///
/// This is the canary for cross-engine corruption: if a foreign module has
/// been registered with `store`, then filling in this host function's
/// `VMFuncRef::wasm_call` finds the foreign engine's `(param f64)` trampoline
/// and the host sees a garbage value instead.
fn observe_i64_in_host(store: &mut Store<()>) -> Result<i64> {
    let observed = Arc::new(Mutex::new(0));
    let host = Func::wrap(&mut *store, {
        let observed = Arc::clone(&observed);
        move |x: i64| *observed.lock().unwrap() = x
    });
    let engine = store.engine().clone();
    let module = Module::new(
        &engine,
        r#"
            (module
                (import "" "" (func $host (param i64)))
                (func (export "go")
                    i64.const 0x1122334455667788
                    call $host))
        "#,
    )?;
    let instance = Instance::new(&mut *store, &module, &[host.into()])?;
    instance
        .get_typed_func::<(), ()>(&mut *store, "go")?
        .call(&mut *store, ())?;
    let observed = *observed.lock().unwrap();
    Ok(observed)
}

/// Asserts that `store` is still usable and that nothing in it confuses one
/// engine's type indices for another's.
fn assert_store_is_uncorrupted(store: &mut Store<()>) -> Result<()> {
    assert_eq!(observe_i64_in_host(store)?, SENTINEL);
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn instance_new_rejects_foreign_module() -> Result<()> {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());
    let foreign = Module::new(&b, COLLIDING_MODULE)?;

    Instance::new(&mut store, &foreign, &[])
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

/// A foreign module's imports must be rejected as cross-engine rather than
/// type checked, since type checking would compare this engine's indices
/// against the foreign engine's.
#[test]
#[cfg_attr(miri, ignore)]
fn instance_new_rejects_foreign_module_with_imports() -> Result<()> {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());

    // Register an unrelated type first so that the host function below does not
    // land on the same index in `a` that the module's imported type lands on in
    // `b`.
    let _ = Func::wrap(&mut store, |_: i32| {});
    let host = Func::wrap(&mut store, |_: i64| {});

    let foreign = Module::new(&b, r#"(module (import "" "" (func (param i64))))"#)?;

    Instance::new(&mut store, &foreign, &[host.into()])
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

/// A linker and the module it instantiates can belong to the same engine while
/// an individual item defined in that linker came from a store belonging to a
/// different one, so each item has to be checked on its own.
#[test]
#[cfg_attr(miri, ignore)]
fn instantiate_pre_rejects_foreign_definition() -> Result<()> {
    let (a, b) = engine_pair();

    // Register an unrelated type first so that the function below does not land
    // on the same index in `b` that the module's imported type lands on in `a`.
    let mut foreign_store = Store::new(&b, ());
    let _ = Func::wrap(&mut foreign_store, |_: i32| {});
    let foreign = Func::wrap(&mut foreign_store, |_: f64| {});

    let mut linker = Linker::<()>::new(&a);
    linker.define(&foreign_store, "", "", foreign)?;

    let module = Module::new(&a, r#"(module (import "" "" (func (param i64))))"#)?;

    linker
        .instantiate_pre(&module)
        .err()
        .expect("should reject an item defined from a different engine's store")
        .assert_contains("cross-`Engine`");

    let mut store = Store::new(&a, ());
    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn instance_pre_instantiate_rejects_foreign_store() -> Result<()> {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());
    let foreign = Module::new(&b, COLLIDING_MODULE)?;
    let pre = Linker::<()>::new(&b).instantiate_pre(&foreign)?;

    pre.instantiate(&mut store)
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn linker_instantiate_pre_rejects_foreign_module() -> Result<()> {
    let (a, b) = engine_pair();
    let foreign = Module::new(&b, COLLIDING_MODULE)?;

    Linker::<()>::new(&a)
        .instantiate_pre(&foreign)
        .err()
        .expect("should reject a module from a different engine")
        .assert_contains("cross-`Engine`");

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn debug_register_module_rejects_foreign_module() -> Result<()> {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());
    let foreign = Module::new(&b, COLLIDING_MODULE)?;

    store
        .debug_register_module(&foreign)
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn debug_register_component_rejects_foreign_component() -> Result<()> {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());
    let foreign = Component::new(&b, COLLIDING_COMPONENT)?;

    store
        .debug_register_component(&foreign)
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn add_breakpoint_rejects_foreign_module() -> Result<()> {
    let (a, b) = engine_pair_with(|config| {
        config.guest_debug(true);
    })?;
    let mut store = Store::new(&a, ());
    let foreign = Module::new(&b, r#"(module (func (export "f") (param f64)))"#)?;

    store
        .edit_breakpoints()
        .unwrap()
        .add_breakpoint(&foreign, ModulePC::new(0))
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn remove_breakpoint_rejects_foreign_module() -> Result<()> {
    let (a, b) = engine_pair_with(|config| {
        config.guest_debug(true);
    })?;
    let mut store = Store::new(&a, ());
    let foreign = Module::new(&b, r#"(module (func (export "f") (param f64)))"#)?;

    store
        .edit_breakpoints()
        .unwrap()
        .remove_breakpoint(&foreign, ModulePC::new(0))
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn component_linker_instantiate_pre_rejects_foreign_component() -> Result<()> {
    let (a, b) = engine_pair();
    let foreign = Component::new(&b, COLLIDING_COMPONENT)?;

    ComponentLinker::<()>::new(&a)
        .instantiate_pre(&foreign)
        .err()
        .expect("should reject a component from a different engine")
        .assert_contains("cross-`Engine`");

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn component_instance_pre_instantiate_rejects_foreign_store() -> Result<()> {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());
    let foreign = Component::new(&b, COLLIDING_COMPONENT)?;
    let pre = ComponentLinker::<()>::new(&b).instantiate_pre(&foreign)?;

    pre.instantiate(&mut store)
        .unwrap_err()
        .assert_contains("cross-`Engine`");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn tag_new_rejects_foreign_type() -> Result<()> {
    let (a, b) = engine_pair_with(|config| {
        config.wasm_exceptions(true);
    })?;
    let mut store = Store::new(&a, ());
    let foreign_ty = TagType::new(FuncType::new(&b, [ValType::I32], []));

    Tag::new(&mut store, &foreign_ty)
        .unwrap_err()
        .assert_contains("wrong engine");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn table_new_rejects_foreign_type() -> Result<()> {
    let (a, b) = engine_pair_with(|config| {
        config.wasm_gc(true);
    })?;
    let mut store = Store::new(&a, ());
    let foreign_struct = StructType::new(
        &b,
        [FieldType::new(
            Mutability::Const,
            StorageType::ValType(ValType::I32),
        )],
    )?;
    let foreign_heap_ty = HeapType::ConcreteStruct(foreign_struct);
    let foreign_ty = TableType::new(RefType::new(true, foreign_heap_ty.clone()), 0, None);

    Table::new(&mut store, foreign_ty, Ref::null(&foreign_heap_ty))
        .unwrap_err()
        .assert_contains("wrong engine");

    assert_store_is_uncorrupted(&mut store)
}

/// Same as [`table_new_rejects_foreign_type`], but for the async variant, which
/// reaches the same check by a different path.
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn table_new_async_rejects_foreign_type() -> Result<()> {
    let (a, b) = engine_pair_with(|config| {
        config.wasm_gc(true);
    })?;
    let mut store = Store::new(&a, ());
    let foreign_struct = StructType::new(
        &b,
        [FieldType::new(
            Mutability::Const,
            StorageType::ValType(ValType::I32),
        )],
    )?;
    let foreign_heap_ty = HeapType::ConcreteStruct(foreign_struct);
    let foreign_ty = TableType::new(RefType::new(true, foreign_heap_ty.clone()), 0, None);

    Table::new_async(&mut store, foreign_ty, Ref::null(&foreign_heap_ty))
        .await
        .unwrap_err()
        .assert_contains("wrong engine");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[cfg_attr(miri, ignore)]
fn global_new_rejects_foreign_type() -> Result<()> {
    let (a, b) = engine_pair_with(|config| {
        config.wasm_gc(true);
    })?;
    let mut store = Store::new(&a, ());
    let foreign_struct = StructType::new(
        &b,
        [FieldType::new(
            Mutability::Const,
            StorageType::ValType(ValType::I32),
        )],
    )?;
    let foreign_heap_ty = HeapType::ConcreteStruct(foreign_struct);
    let foreign_ty = GlobalType::new(
        ValType::Ref(RefType::new(true, foreign_heap_ty.clone())),
        Mutability::Const,
    );

    Global::new(&mut store, foreign_ty, Ref::null(&foreign_heap_ty).into())
        .unwrap_err()
        .assert_contains("wrong engine");

    assert_store_is_uncorrupted(&mut store)
}

#[test]
#[should_panic = "wrong engine"]
fn struct_ref_pre_rejects_foreign_type() {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());
    let foreign_ty = StructType::new(
        &b,
        [FieldType::new(
            Mutability::Const,
            StorageType::ValType(ValType::I32),
        )],
    )
    .unwrap();

    let _ = StructRefPre::new(&mut store, foreign_ty);
}

#[test]
#[should_panic = "wrong engine"]
fn array_ref_pre_rejects_foreign_type() {
    let (a, b) = engine_pair();
    let mut store = Store::new(&a, ());
    let foreign_ty = ArrayType::new(
        &b,
        FieldType::new(Mutability::Const, StorageType::ValType(ValType::I32)),
    );

    let _ = ArrayRefPre::new(&mut store, foreign_ty);
}

#[test]
#[should_panic = "wrong engine"]
fn exn_ref_pre_rejects_foreign_type() {
    let (a, b) = engine_pair_with(|config| {
        config.wasm_exceptions(true);
    })
    .unwrap();
    let mut store = Store::new(&a, ());
    let foreign_ty = ExnType::new(&b, [ValType::I32]).unwrap();

    let _ = ExnRefPre::new(&mut store, foreign_ty);
}