wasmtime-internal-debugger 44.0.1

INTERNAL: Wasmtime's guest-debugger functionality
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
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
//! A type-erased trait wrapping the `Debugger<T>` to permit its use
//! within a resource.

use crate::host::wit;
use crate::host::{api::WasmValue, bindings::val_type_to_wasm_type};
use wasmtime::{
    Engine, ExnRef, ExnRefPre, ExnType, FrameHandle, Func, FuncType, Global, Instance, Memory,
    Module, OwnedRooted, Result, Table, Tag, TagType, Val, ValType,
};

/// Type-erased interface to the `Debugger<T>` implementing all
/// functionality necessary for the interfaces here. This needs to be
/// type-erased because the host-side resource APIs do not support
/// type-parameterized resource kinds -- e.g., we cannot have a
/// resource for a `Debugger<T>`, only a `Debugger`, so the debuggee
/// resource essentially needs to carry a vtable for the kind of store
/// the debuggee has.
///
/// Methods here return `wasmtime::Result<T>`, where `Err` may wrap
/// either a `wit::Error` (which `convert_error` will extract and
/// return as an in-band WIT-level error to the component) or any
/// other error (which becomes a trap).
///
/// These methods do not handle the "wrong state" errors (i.e.,
/// execution is continuing so we cannot query store state): those are
/// handled one level up, via moving ownership of the instance of this
/// trait between the execution future and the debuggee resource
/// itself.
#[async_trait::async_trait]
pub(crate) trait OpaqueDebugger {
    async fn all_instances(&mut self) -> Result<Vec<Instance>>;
    async fn all_modules(&mut self) -> Result<Vec<Module>>;
    async fn handle_resumption(&mut self, resumption: &wit::ResumptionValue) -> Result<()>;
    async fn single_step(&mut self) -> Result<crate::DebugRunResult>;
    async fn continue_(&mut self) -> Result<crate::DebugRunResult>;
    async fn exit_frames(&mut self) -> Result<Vec<FrameHandle>>;
    async fn get_instance_module(&mut self, instance: Instance) -> Result<Module>;

    async fn instance_get_memory(&mut self, instance: Instance, idx: u32)
    -> Result<Option<Memory>>;
    async fn instance_get_global(&mut self, instance: Instance, idx: u32)
    -> Result<Option<Global>>;
    async fn instance_get_table(&mut self, instance: Instance, idx: u32) -> Result<Option<Table>>;
    async fn instance_get_func(&mut self, instance: Instance, idx: u32) -> Result<Option<Func>>;
    async fn instance_get_tag(&mut self, instance: Instance, idx: u32) -> Result<Option<Tag>>;

    async fn memory_size_bytes(&mut self, memory: Memory) -> Result<u64>;
    async fn memory_page_size(&mut self, memory: Memory) -> Result<u64>;
    async fn memory_grow(&mut self, memory: Memory, delta_bytes: u64) -> Result<u64>;
    async fn memory_read_bytes(
        &mut self,
        memory: Memory,
        addr: u64,
        len: u64,
    ) -> Result<Option<Vec<u8>>>;
    async fn memory_write_bytes(
        &mut self,
        memory: Memory,
        addr: u64,
        bytes: Vec<u8>,
    ) -> Result<Option<()>>;
    async fn memory_read_u8(&mut self, memory: Memory, addr: u64) -> Result<Option<u8>>;
    async fn memory_read_u16(&mut self, memory: Memory, addr: u64) -> Result<Option<u16>>;
    async fn memory_read_u32(&mut self, memory: Memory, addr: u64) -> Result<Option<u32>>;
    async fn memory_read_u64(&mut self, memory: Memory, addr: u64) -> Result<Option<u64>>;
    async fn memory_write_u8(&mut self, memory: Memory, addr: u64, data: u8) -> Result<Option<()>>;
    async fn memory_write_u16(
        &mut self,
        memory: Memory,
        addr: u64,
        data: u16,
    ) -> Result<Option<()>>;
    async fn memory_write_u32(
        &mut self,
        memory: Memory,
        addr: u64,
        data: u32,
    ) -> Result<Option<()>>;
    async fn memory_write_u64(
        &mut self,
        memory: Memory,
        addr: u64,
        data: u64,
    ) -> Result<Option<()>>;

    async fn global_get(&mut self, global: Global) -> Result<WasmValue>;
    async fn global_set(&mut self, global: Global, val: WasmValue) -> Result<()>;

    async fn table_len(&mut self, table: Table) -> Result<u64>;
    async fn table_get_element(&mut self, table: Table, index: u64) -> Result<WasmValue>;
    async fn table_set_element(&mut self, table: Table, index: u64, val: WasmValue) -> Result<()>;

    async fn func_params(&mut self, func: Func) -> Result<Vec<wit::WasmType>>;
    async fn func_results(&mut self, func: Func) -> Result<Vec<wit::WasmType>>;

    async fn tag_params(&mut self, tag: Tag) -> Result<Vec<wit::WasmType>>;
    async fn tag_new(&mut self, engine: Engine, params: Vec<ValType>) -> Result<Tag>;

    async fn exnref_get_tag(&mut self, exn: OwnedRooted<ExnRef>) -> Result<Tag>;
    async fn exnref_get_fields(&mut self, exn: OwnedRooted<ExnRef>) -> Result<Vec<WasmValue>>;
    async fn exnref_new(&mut self, tag: Tag, fields: Vec<WasmValue>)
    -> Result<OwnedRooted<ExnRef>>;

    async fn frame_instance(&mut self, frame: FrameHandle) -> Result<Instance>;
    async fn frame_func_and_pc(&mut self, frame: FrameHandle) -> Result<(u32, u32)>;
    async fn frame_locals(&mut self, frame: FrameHandle) -> Result<Vec<WasmValue>>;
    async fn frame_stack(&mut self, frame: FrameHandle) -> Result<Vec<WasmValue>>;
    async fn frame_parent(&mut self, frame: FrameHandle) -> Result<Option<FrameHandle>>;

    async fn module_add_breakpoint(&mut self, module: Module, pc: u32) -> Result<()>;
    async fn module_remove_breakpoint(&mut self, module: Module, pc: u32) -> Result<()>;

    async fn finish(&mut self) -> Result<()>;
}

#[async_trait::async_trait]
impl<T: Send + 'static> OpaqueDebugger for crate::Debuggee<T> {
    async fn all_instances(&mut self) -> Result<Vec<Instance>> {
        self.with_store(|store| store.debug_all_instances()).await
    }

    async fn all_modules(&mut self) -> Result<Vec<Module>> {
        self.with_store(|store| store.debug_all_modules()).await
    }

    async fn single_step(&mut self) -> Result<crate::DebugRunResult> {
        self.with_store(|store| store.edit_breakpoints().unwrap().single_step(true).unwrap())
            .await?;

        self.run().await
    }

    async fn continue_(&mut self) -> Result<crate::DebugRunResult> {
        self.with_store(|store| {
            store
                .edit_breakpoints()
                .unwrap()
                .single_step(false)
                .unwrap()
        })
        .await?;

        self.run().await
    }

    async fn handle_resumption(&mut self, resumption: &wit::ResumptionValue) -> Result<()> {
        match resumption {
            wit::ResumptionValue::Normal => {}
            _ => {
                unimplemented!("Non-`Normal` resumption not yet supported");
            }
        }
        Ok(())
    }

    async fn exit_frames(&mut self) -> Result<Vec<FrameHandle>> {
        self.with_store(|mut store| store.debug_exit_frames().collect::<Vec<_>>())
            .await
    }

    async fn get_instance_module(&mut self, instance: Instance) -> Result<Module> {
        self.with_store(move |store| instance.module(&store).clone())
            .await
    }

    async fn instance_get_memory(
        &mut self,
        instance: Instance,
        idx: u32,
    ) -> Result<Option<Memory>> {
        self.with_store(move |mut store| instance.debug_memory(&mut store, idx))
            .await
    }

    async fn instance_get_global(
        &mut self,
        instance: Instance,
        idx: u32,
    ) -> Result<Option<Global>> {
        self.with_store(move |mut store| instance.debug_global(&mut store, idx))
            .await
    }

    async fn instance_get_table(&mut self, instance: Instance, idx: u32) -> Result<Option<Table>> {
        self.with_store(move |mut store| instance.debug_table(&mut store, idx))
            .await
    }

    async fn instance_get_func(&mut self, instance: Instance, idx: u32) -> Result<Option<Func>> {
        self.with_store(move |mut store| instance.debug_function(&mut store, idx))
            .await
    }

    async fn instance_get_tag(&mut self, instance: Instance, idx: u32) -> Result<Option<Tag>> {
        self.with_store(move |mut store| instance.debug_tag(&mut store, idx))
            .await
    }

    async fn memory_size_bytes(&mut self, memory: Memory) -> Result<u64> {
        self.with_store(move |store| u64::try_from(memory.data_size(&store)).unwrap())
            .await
    }

    async fn memory_page_size(&mut self, memory: Memory) -> Result<u64> {
        self.with_store(move |store| memory.page_size(&store)).await
    }

    async fn memory_grow(&mut self, memory: Memory, delta_bytes: u64) -> Result<u64> {
        self.with_store(move |mut store| -> Result<u64> {
            let page_size = memory.page_size(&store);
            if delta_bytes & (page_size - 1) != 0 {
                return Err(wit::Error::MemoryGrowFailure.into());
            }
            let delta_pages = delta_bytes / page_size;
            let old_pages = memory
                .grow(&mut store, delta_pages)
                .map_err(|_| wit::Error::MemoryGrowFailure)?;
            Ok(old_pages * page_size)
        })
        .await?
    }

    async fn memory_read_bytes(
        &mut self,
        memory: Memory,
        addr: u64,
        len: u64,
    ) -> Result<Option<Vec<u8>>> {
        self.with_store(move |store| {
            let data = memory.data(&store);
            let addr = usize::try_from(addr).unwrap();
            let len = usize::try_from(len).unwrap();
            data.get(addr..addr + len).map(|s| s.to_vec())
        })
        .await
    }

    async fn memory_write_bytes(
        &mut self,
        memory: Memory,
        addr: u64,
        bytes: Vec<u8>,
    ) -> Result<Option<()>> {
        self.with_store(move |mut store| {
            let data = memory.data_mut(&mut store);
            let addr = usize::try_from(addr).unwrap();
            let dest = data.get_mut(addr..addr + bytes.len())?;
            dest.copy_from_slice(&bytes);
            Some(())
        })
        .await
    }

    async fn memory_read_u8(&mut self, memory: Memory, addr: u64) -> Result<Option<u8>> {
        self.with_store(move |store| {
            let data = memory.data(&store);
            let addr = usize::try_from(addr).unwrap();
            Some(*data.get(addr)?)
        })
        .await
    }

    async fn memory_read_u16(&mut self, memory: Memory, addr: u64) -> Result<Option<u16>> {
        self.with_store(move |store| {
            let data = memory.data(&store);
            let addr = usize::try_from(addr).unwrap();
            Some(u16::from_le_bytes([*data.get(addr)?, *data.get(addr + 1)?]))
        })
        .await
    }

    async fn memory_read_u32(&mut self, memory: Memory, addr: u64) -> Result<Option<u32>> {
        self.with_store(move |store| {
            let data = memory.data(&store);
            let addr = usize::try_from(addr).unwrap();
            Some(u32::from_le_bytes([
                *data.get(addr)?,
                *data.get(addr + 1)?,
                *data.get(addr + 2)?,
                *data.get(addr + 3)?,
            ]))
        })
        .await
    }

    async fn memory_read_u64(&mut self, memory: Memory, addr: u64) -> Result<Option<u64>> {
        self.with_store(move |store| {
            let data = memory.data(&store);
            let addr = usize::try_from(addr).unwrap();
            Some(u64::from_le_bytes([
                *data.get(addr)?,
                *data.get(addr + 1)?,
                *data.get(addr + 2)?,
                *data.get(addr + 3)?,
                *data.get(addr + 4)?,
                *data.get(addr + 5)?,
                *data.get(addr + 6)?,
                *data.get(addr + 7)?,
            ]))
        })
        .await
    }

    async fn memory_write_u8(
        &mut self,
        memory: Memory,
        addr: u64,
        value: u8,
    ) -> Result<Option<()>> {
        self.with_store(move |mut store| {
            let data = memory.data_mut(&mut store);
            let addr = usize::try_from(addr).unwrap();
            *data.get_mut(addr)? = value;
            Some(())
        })
        .await
    }

    async fn memory_write_u16(
        &mut self,
        memory: Memory,
        addr: u64,
        value: u16,
    ) -> Result<Option<()>> {
        self.with_store(move |mut store| {
            let data = memory.data_mut(&mut store);
            let addr = usize::try_from(addr).unwrap();
            data.get_mut(addr..(addr + 2))?
                .copy_from_slice(&value.to_le_bytes());
            Some(())
        })
        .await
    }

    async fn memory_write_u32(
        &mut self,
        memory: Memory,
        addr: u64,
        value: u32,
    ) -> Result<Option<()>> {
        self.with_store(move |mut store| {
            let data = memory.data_mut(&mut store);
            let addr = usize::try_from(addr).unwrap();
            data.get_mut(addr..(addr + 4))?
                .copy_from_slice(&value.to_le_bytes());
            Some(())
        })
        .await
    }

    async fn memory_write_u64(
        &mut self,
        memory: Memory,
        addr: u64,
        value: u64,
    ) -> Result<Option<()>> {
        self.with_store(move |mut store| {
            let data = memory.data_mut(&mut store);
            let addr = usize::try_from(addr).unwrap();
            data.get_mut(addr..(addr + 8))?
                .copy_from_slice(&value.to_le_bytes());
            Some(())
        })
        .await
    }

    async fn global_get(&mut self, global: Global) -> Result<WasmValue> {
        self.with_store(move |mut store| {
            let val = global.get(&mut store);
            WasmValue::new(&mut store, val)
        })
        .await?
    }

    async fn global_set(&mut self, global: Global, val: WasmValue) -> Result<()> {
        self.with_store(move |mut store| -> Result<()> {
            let v = val.into_val(&mut store);
            global
                .set(&mut store, v)
                .map_err(|_| wit::Error::MismatchedType)?;
            Ok(())
        })
        .await?
    }

    async fn table_len(&mut self, table: Table) -> Result<u64> {
        self.with_store(move |store| table.size(&store)).await
    }

    async fn table_get_element(&mut self, table: Table, index: u64) -> Result<WasmValue> {
        self.with_store(move |mut store| -> Result<WasmValue> {
            let val = table
                .get(&mut store, index)
                .ok_or(wit::Error::OutOfBounds)?;
            WasmValue::new(&mut store, val.into())
        })
        .await?
    }

    async fn table_set_element(&mut self, table: Table, index: u64, val: WasmValue) -> Result<()> {
        self.with_store(move |mut store| -> Result<()> {
            let v = val.into_val(&mut store);
            let r = v.ref_().ok_or(wit::Error::MismatchedType)?;
            table
                .set(&mut store, index, r)
                .map_err(|_| wit::Error::MismatchedType)?;
            Ok(())
        })
        .await?
    }

    async fn func_params(&mut self, func: Func) -> Result<Vec<wit::WasmType>> {
        self.with_store(move |store| {
            let ty = func.ty(&store);
            ty.params()
                .map(|ty| val_type_to_wasm_type(&ty))
                .collect::<Result<Vec<_>>>()
        })
        .await?
    }

    async fn func_results(&mut self, func: Func) -> Result<Vec<wit::WasmType>> {
        self.with_store(move |store| {
            let ty = func.ty(&store);
            ty.results()
                .map(|ty| val_type_to_wasm_type(&ty))
                .collect::<Result<Vec<_>>>()
        })
        .await?
    }

    async fn tag_params(&mut self, tag: Tag) -> Result<Vec<wit::WasmType>> {
        self.with_store(move |store| {
            let ty = tag.ty(&store);
            ty.ty()
                .params()
                .map(|ty| val_type_to_wasm_type(&ty))
                .collect::<Result<Vec<_>>>()
        })
        .await?
    }

    async fn tag_new(&mut self, engine: Engine, params: Vec<ValType>) -> Result<Tag> {
        self.with_store(move |mut store| {
            let func_ty = FuncType::new(&engine, params, []);
            let tag_ty = TagType::new(func_ty);
            Tag::new(&mut store, &tag_ty)
        })
        .await?
    }

    async fn exnref_get_tag(&mut self, exn: OwnedRooted<ExnRef>) -> Result<Tag> {
        self.with_store(move |mut store| exn.tag(&mut store).expect("reference must be rooted"))
            .await
    }

    async fn exnref_get_fields(&mut self, exn: OwnedRooted<ExnRef>) -> Result<Vec<WasmValue>> {
        self.with_store(move |mut store| {
            let fields = exn
                .fields(&mut store)
                .expect("reference must be rooted")
                .collect::<Vec<Val>>();
            fields
                .into_iter()
                .map(|v| WasmValue::new(&mut store, v))
                .collect::<Result<Vec<_>>>()
        })
        .await?
    }

    async fn exnref_new(
        &mut self,
        tag: Tag,
        fields: Vec<WasmValue>,
    ) -> Result<OwnedRooted<ExnRef>> {
        self.with_store(move |mut store| -> Result<OwnedRooted<ExnRef>> {
            let exn_ty =
                ExnType::from_tag_type(&tag.ty(&store)).expect("tag type is already validated");
            let allocator = ExnRefPre::new(&mut store, exn_ty);
            let field_vals = fields
                .into_iter()
                .map(|v| v.into_val(&mut store))
                .collect::<Vec<_>>();
            let exn = ExnRef::new(&mut store, &allocator, &tag, &field_vals)
                .map_err(|_| wit::Error::AllocFailure)?;
            Ok(exn.to_owned_rooted(&mut store).unwrap())
        })
        .await?
    }

    async fn frame_instance(&mut self, frame: FrameHandle) -> Result<Instance> {
        self.with_store(move |mut store| -> Result<Instance> {
            Ok(frame
                .instance(&mut store)
                .map_err(|_| wit::Error::InvalidFrame)?)
        })
        .await?
    }

    async fn frame_func_and_pc(&mut self, frame: FrameHandle) -> Result<(u32, u32)> {
        self.with_store(move |mut store| -> Result<(u32, u32)> {
            let (func, pc) = frame
                .wasm_function_index_and_pc(&mut store)
                .map_err(|_| wit::Error::InvalidFrame)?
                .ok_or(wit::Error::NonWasmFrame)?;
            Ok((func.as_u32(), pc.raw()))
        })
        .await?
    }

    async fn frame_locals(&mut self, frame: FrameHandle) -> Result<Vec<WasmValue>> {
        self.with_store(move |mut store| -> Result<Vec<WasmValue>> {
            let n_locals = frame
                .num_locals(&mut store)
                .map_err(|_| wit::Error::InvalidFrame)?;
            let mut result = vec![];
            for i in 0..n_locals {
                let val = frame
                    .local(&mut store, i)
                    .expect("checked for validity above");
                result.push(WasmValue::new(&mut store, val)?);
            }
            Ok(result)
        })
        .await?
    }

    async fn frame_stack(&mut self, frame: FrameHandle) -> Result<Vec<WasmValue>> {
        self.with_store(move |mut store| -> Result<Vec<WasmValue>> {
            let n_stacks = frame
                .num_stacks(&mut store)
                .map_err(|_| wit::Error::InvalidFrame)?;
            let mut result = vec![];
            for i in 0..n_stacks {
                let val = frame
                    .stack(&mut store, i)
                    .expect("checked for validity above");
                result.push(WasmValue::new(&mut store, val)?);
            }
            Ok(result)
        })
        .await?
    }

    async fn frame_parent(&mut self, frame: FrameHandle) -> Result<Option<FrameHandle>> {
        self.with_store(move |mut store| -> Result<Option<FrameHandle>> {
            Ok(frame
                .parent(&mut store)
                .map_err(|_| wit::Error::InvalidFrame)?)
        })
        .await?
    }

    async fn module_add_breakpoint(&mut self, module: Module, pc: u32) -> Result<()> {
        self.with_store(move |store| -> Result<()> {
            store
                .edit_breakpoints()
                .expect("guest debugging is enabled")
                .add_breakpoint(&module, wasmtime::ModulePC::new(pc))
                .map_err(|_| wit::Error::InvalidPc)?;
            Ok(())
        })
        .await?
    }

    async fn module_remove_breakpoint(&mut self, module: Module, pc: u32) -> Result<()> {
        self.with_store(move |store| -> Result<()> {
            store
                .edit_breakpoints()
                .expect("guest debugging is enabled")
                .remove_breakpoint(&module, wasmtime::ModulePC::new(pc))
                .map_err(|_| wit::Error::InvalidPc)?;
            Ok(())
        })
        .await?
    }

    async fn finish(&mut self) -> Result<()> {
        self.finish().await?;
        Ok(())
    }
}