1use std::collections::{HashMap, HashSet};
6use std::future::Future;
7use std::pin::Pin;
8use std::sync::{Arc, OnceLock};
9use std::task::Poll;
10use std::time::{Duration, Instant};
11
12use wasmtime::{Caller, Config, Engine, Instance, Linker, Memory, Module, Store, TypedFunc, bail, format_err};
13
14use crate::assets::Assets;
15use crate::audio::AudioOut;
16use crate::gfx::Gfx;
17use crate::net::Net;
18use crate::present::letterbox;
19use crate::storage::Storage;
20use crate::switching::{self, Cmd, Exchange, Job};
21use crate::wasi::{self, Splitmix};
22
23pub const ABI_VERSION: i32 = 0;
24
25#[derive(Clone, Copy)]
27pub struct Fnv(pub u32);
28
29impl Default for Fnv {
30 fn default() -> Self {
31 Fnv(0x811c_9dc5)
32 }
33}
34
35impl Fnv {
36 pub fn new() -> Self {
37 Self::default()
38 }
39 pub fn update(&mut self, bytes: &[u8]) {
40 let mut h = self.0;
41 for &b in bytes {
42 h ^= b as u32;
43 h = h.wrapping_mul(0x0100_0193);
44 }
45 self.0 = h;
46 }
47}
48
49#[derive(Clone, Copy)]
53pub struct VirtualClock {
54 base_ms: f64,
55 base_frame: u64,
56 rate: f64,
57}
58
59impl Default for VirtualClock {
60 fn default() -> Self {
61 VirtualClock { base_ms: 0.0, base_frame: 0, rate: 60.0 }
62 }
63}
64
65impl VirtualClock {
66 pub fn at(&mut self, frame: u64, rate: f64) -> f64 {
68 if rate != self.rate {
69 self.base_ms += (frame - self.base_frame) as f64 * 1000.0 / self.rate;
70 self.base_frame = frame;
71 self.rate = rate;
72 }
73 self.base_ms + (frame - self.base_frame) as f64 * 1000.0 / self.rate
74 }
75}
76
77#[derive(Default, Clone)]
80pub struct RawInput {
81 pub keys: Option<[u8; KEY_STATE_BYTES]>,
83 pub key_events: Vec<(u16, bool)>,
85 pub pointer: Option<Pointer>,
86 pub gamepads: Option<[Gamepad; 4]>,
87}
88
89pub const KEY_STATE_BYTES: usize = 32;
90pub const POINTER_BYTES: usize = 48;
91pub const GAMEPAD_BYTES: usize = 204;
92pub const GAMEPAD_BUTTONS: usize = 32;
93pub const GAMEPAD_AXES: usize = 16;
94
95#[derive(Default, Clone, Copy)]
96pub struct Pointer {
97 pub x: f32,
99 pub y: f32,
100 pub dx: f32,
101 pub dy: f32,
102 pub wheel_x: f32,
103 pub wheel_y: f32,
104 pub buttons: u32,
105 pub pressed: u32,
106 pub released: u32,
107 pub flags: u32,
109 pub drawable: (f32, f32),
111 pub integer_scale: bool,
113}
114
115#[derive(Default, Clone)]
116pub struct Gamepad {
117 pub connected: bool,
118 pub standard: bool,
119 pub buttons: Vec<f32>,
120 pub axes: Vec<f32>,
121 pub name: String,
122}
123
124pub fn frame_position(x: f32, y: f32, drawable: (f32, f32), frame: (usize, usize), integer_scale: bool, aspect: Option<(u32, u32)>) -> (f32, f32) {
127 if frame.0 == 0 || frame.1 == 0 || drawable.0 <= 0.0 || drawable.1 <= 0.0 {
128 return (x, y);
129 }
130 let (ox, oy, sx, sy) = letterbox((drawable.0 as f64, drawable.1 as f64), (frame.0 as f64, frame.1 as f64), integer_scale, aspect);
131 (((x as f64 - ox) / sx) as f32, ((y as f64 - oy) / sy) as f32)
132}
133
134pub const TITLE_MAX_BYTES: usize = 256;
136
137pub fn clean_title(text: &str) -> Option<String> {
142 let mut out = String::new();
143 for c in text.chars().filter(|&c| !c.is_control() && !matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) {
144 if out.len() + c.len_utf8() > TITLE_MAX_BYTES {
145 break;
146 }
147 out.push(c);
148 }
149 (!out.is_empty()).then_some(out)
150}
151
152pub fn custom_section<'a>(wasm: &'a [u8], name: &str) -> Option<&'a [u8]> {
155 fn leb(b: &[u8], at: &mut usize) -> Option<usize> {
156 let (mut v, mut shift) = (0usize, 0);
157 loop {
158 let byte = *b.get(*at)?;
159 *at += 1;
160 v |= ((byte & 0x7f) as usize).checked_shl(shift)?;
161 if byte & 0x80 == 0 {
162 return Some(v);
163 }
164 shift += 7;
165 if shift > 28 {
166 return None;
167 }
168 }
169 }
170 if wasm.get(..4)? != b"\0asm" {
171 return None;
172 }
173 let mut at = 8;
174 while at < wasm.len() {
175 let id = wasm[at];
176 at += 1;
177 let size = leb(wasm, &mut at)?;
178 let body = wasm.get(at..at.checked_add(size)?)?;
179 at += size;
180 if id == 0 {
181 let mut p = 0;
182 let n = leb(body, &mut p)?;
183 if body.get(p..p.checked_add(n)?)? == name.as_bytes() {
184 return body.get(p + n..);
185 }
186 }
187 }
188 None
189}
190
191pub fn static_title(wasm: &[u8]) -> Option<String> {
194 clean_title(std::str::from_utf8(custom_section(wasm, "gasm.title")?).ok()?)
195}
196
197pub struct Host {
198 memory: Option<Memory>,
199 start: Instant,
200 pub virtual_time_ms: Option<f64>,
203 pub random: Option<Splitmix>,
205 pub frame_rate: f64,
206 pub pads: [u32; 4],
207 pub text: Option<String>,
210 pub input: RawInput,
211 pub input_mode: u32,
213 pub assets: Assets,
214 pub params: HashMap<String, String>,
215 pub audio: Option<Box<dyn AudioOut>>,
216 pub gfx: Gfx,
217 pub gl: crate::gl::Gl,
219 pub frame_index: u64,
221 pub net: Net,
222 pub storage: Storage,
223 pub show_frame: bool,
225 audio_rate: u32,
226 audio_channels: u32,
227 provided: HashSet<String>,
229 pub rgba: Vec<u8>,
231 pub width: usize,
232 pub height: usize,
233 pub frames_presented: u64,
234 pub aspect: Option<(u32, u32)>,
236 pub(crate) run: Option<Arc<Exchange>>,
238 pub title: Option<String>,
240 pub title_changed: bool,
242 pub hashing: bool,
243 pub video_hash: Fnv,
244 pub audio_hash: Fnv,
245 pub audio_frames: u64,
246}
247
248impl Host {
249 pub fn new(
250 assets: impl Into<Assets>,
251 params: HashMap<String, String>,
252 audio: Option<Box<dyn AudioOut>>,
253 gfx: Gfx,
254 net: Net,
255 storage: Storage,
256 ) -> Self {
257 Host {
258 memory: None,
259 start: Instant::now(),
260 virtual_time_ms: None,
261 random: None,
262 frame_rate: 60.0,
263 pads: [0; 4],
264 text: None,
265 input: RawInput::default(),
266 input_mode: 0,
267 assets: assets.into(),
268 params,
269 audio,
270 gfx,
271 gl: Default::default(),
272 frame_index: 0,
273 net,
274 storage,
275 show_frame: true,
276 audio_rate: 44100,
277 audio_channels: 2,
278 provided: HashSet::new(),
279 title: None,
280 title_changed: false,
281 aspect: None,
282 run: None,
283 rgba: Vec::new(),
284 width: 0,
285 height: 0,
286 frames_presented: 0,
287 hashing: true,
288 video_hash: Fnv::new(),
289 audio_hash: Fnv::new(),
290 audio_frames: 0,
291 }
292 }
293
294 pub fn set_reproducible(&mut self) {
297 self.virtual_time_ms = Some(0.0);
298 self.random = Some(Splitmix(0));
299 }
300
301 pub(crate) fn started(&self) -> Instant {
302 self.start
303 }
304}
305
306pub fn imports_module(wasm: &[u8], module: &str, allow_precompiled: bool) -> bool {
309 if !wasm.starts_with(b"\0asm") {
310 if !allow_precompiled {
311 return false;
312 }
313 return unsafe { Module::deserialize(engine(), wasm) }.is_ok_and(|m| m.imports().any(|i| i.module() == module));
314 }
315 fn leb(b: &[u8], p: &mut usize) -> Option<u32> {
316 let (mut v, mut shift) = (0u32, 0);
317 loop {
318 let byte = *b.get(*p)?;
319 *p += 1;
320 v |= ((byte & 0x7f) as u32) << shift;
321 if byte & 0x80 == 0 {
322 return Some(v);
323 }
324 shift += 7;
325 if shift > 28 {
326 return None;
327 }
328 }
329 }
330 fn name<'a>(b: &'a [u8], p: &mut usize) -> Option<&'a [u8]> {
331 let n = leb(b, p)? as usize;
332 let s = b.get(*p..*p + n)?;
333 *p += n;
334 Some(s)
335 }
336 let scan = || -> Option<bool> {
337 let mut p = 8;
338 while p < wasm.len() {
339 let id = wasm[p];
340 p += 1;
341 let size = leb(wasm, &mut p)? as usize;
342 let end = p.checked_add(size)?;
343 if id == 2 {
344 let mut q = p;
345 for _ in 0..leb(wasm, &mut q)? {
346 if name(wasm, &mut q)? == module.as_bytes() {
347 return Some(true);
348 }
349 name(wasm, &mut q)?;
350 match *wasm.get(q)? {
351 0 => { q += 1; leb(wasm, &mut q)?; } 1 => { q += 2; let f = wasm[q - 1]; leb(wasm, &mut q)?; if f & 1 != 0 { leb(wasm, &mut q)?; } } 2 => { q += 1; let f = *wasm.get(q)?; q += 1; leb(wasm, &mut q)?; if f & 1 != 0 { leb(wasm, &mut q)?; } } 3 => q += 3, 4 => { q += 2; leb(wasm, &mut q)?; } _ => return None,
357 }
358 }
359 return Some(false);
360 }
361 p = end;
362 }
363 Some(false)
364 };
365 scan().unwrap_or(false)
366}
367
368pub(crate) fn guest_slice(mem: &[u8], ptr: u32, len: u64) -> wasmtime::Result<&[u8]> {
370 let start = ptr as u64;
371 let end = start.checked_add(len).ok_or_else(|| format_err!("guest pointer overflow"))?;
372 if end > mem.len() as u64 {
373 bail!("guest access out of bounds: {start:#x}..{end:#x} (memory is {:#x})", mem.len());
374 }
375 Ok(&mem[start as usize..end as usize])
376}
377
378pub(crate) fn guest_slice_mut(mem: &mut [u8], ptr: u32, len: u64) -> wasmtime::Result<&mut [u8]> {
380 let start = ptr as u64;
381 let end = start.checked_add(len).ok_or_else(|| format_err!("guest pointer overflow"))?;
382 if end > mem.len() as u64 {
383 bail!("guest access out of bounds: {start:#x}..{end:#x} (memory is {:#x})", mem.len());
384 }
385 Ok(&mut mem[start as usize..end as usize])
386}
387
388fn copy_if_fits(mem: &mut [u8], dst: u32, cap: u32, src: &[u8]) -> wasmtime::Result<i32> {
391 if src.len() <= cap as usize {
392 guest_slice_mut(mem, dst, src.len() as u64)?.copy_from_slice(src);
393 }
394 Ok(src.len() as i32)
395}
396
397pub(crate) fn memory(caller: &Caller<'_, Host>) -> wasmtime::Result<Memory> {
398 caller.data().memory.ok_or_else(|| format_err!("guest memory not yet available"))
399}
400
401fn guest_str(caller: &Caller<'_, Host>, ptr: u32, len: u32) -> wasmtime::Result<String> {
402 let mem = memory(caller)?;
403 let bytes = guest_slice(mem.data(caller), ptr, len as u64)?;
404 std::str::from_utf8(bytes).map(str::to_owned).map_err(|e| format_err!("string argument is not UTF-8: {e}"))
405}
406
407fn pointer_bytes(p: &Pointer, frame: (usize, usize), aspect: Option<(u32, u32)>) -> [u8; POINTER_BYTES] {
409 let (fx, fy) = frame_position(p.x, p.y, p.drawable, frame, p.integer_scale, aspect);
410 let mut b = [0u8; POINTER_BYTES];
411 for (i, v) in [p.x, p.y, fx, fy, p.dx, p.dy, p.wheel_x, p.wheel_y].into_iter().enumerate() {
412 b[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
413 }
414 for (i, v) in [p.buttons, p.pressed, p.released, p.flags].into_iter().enumerate() {
415 b[32 + i * 4..36 + i * 4].copy_from_slice(&v.to_le_bytes());
416 }
417 b
418}
419
420fn gamepad_bytes(g: &Gamepad) -> [u8; GAMEPAD_BYTES] {
422 let mut b = [0u8; GAMEPAD_BYTES];
423 let nb = g.buttons.len().min(GAMEPAD_BUTTONS);
424 let na = g.axes.len().min(GAMEPAD_AXES);
425 let flags = if g.connected { 1 | if g.standard { 2 } else { 0 } } else { 0u32 };
426 for (i, v) in [flags, nb as u32, na as u32].into_iter().enumerate() {
427 b[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
428 }
429 for (i, v) in g.buttons.iter().take(nb).enumerate() {
430 b[12 + i * 4..16 + i * 4].copy_from_slice(&v.to_le_bytes());
431 }
432 for (i, v) in g.axes.iter().take(na).enumerate() {
433 b[140 + i * 4..144 + i * 4].copy_from_slice(&v.to_le_bytes());
434 }
435 b
436}
437
438fn add_gasm_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
439 linker.func_wrap("gasm", "log", |caller: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<()> {
440 let mem = memory(&caller)?;
441 let msg = guest_slice(mem.data(&caller), ptr, len as u64)?;
442 eprintln!("[guest] {}", String::from_utf8_lossy(msg));
443 Ok(())
444 })?;
445
446 linker.func_wrap("gasm", "has", |caller: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<i32> {
447 let name = guest_str(&caller, ptr, len)?;
448 Ok(caller.data().provided.contains(&name) as i32)
449 })?;
450
451 linker.func_wrap("gasm", "video_set_aspect", |mut caller: Caller<'_, Host>, num: u32, den: u32| -> wasmtime::Result<()> {
452 let aspect = match (num, den) {
453 (0, 0) => None,
454 (1..=65535, 1..=65535) if num as u64 * 8 >= den as u64 && den as u64 * 8 >= num as u64 => Some((num, den)),
455 _ => bail!("video_set_aspect: invalid ratio {num}:{den}"),
456 };
457 caller.data_mut().aspect = aspect;
458 Ok(())
459 })?;
460
461 linker.func_wrap("gasm", "set_title", |mut caller: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<()> {
462 let title = clean_title(&guest_str(&caller, ptr, len)?);
463 let h = caller.data_mut();
464 if h.title != title {
465 h.title = title;
466 h.title_changed = true;
467 }
468 Ok(())
469 })?;
470
471 linker.func_wrap("gasm", "time_ms", |caller: Caller<'_, Host>| -> f64 {
472 let h = caller.data();
473 h.virtual_time_ms.unwrap_or_else(|| h.start.elapsed().as_secs_f64() * 1000.0)
474 })?;
475
476 linker.func_wrap("gasm", "set_frame_rate", |mut caller: Caller<'_, Host>, hz: f64| {
477 if hz.is_finite() && (1.0..=1000.0).contains(&hz) {
478 caller.data_mut().frame_rate = hz;
479 }
480 })?;
481
482 linker.func_wrap(
483 "gasm",
484 "video_present",
485 |mut caller: Caller<'_, Host>, ptr: u32, w: u32, h: u32, stride: u32| -> wasmtime::Result<()> {
486 let (w, h, stride) = (w as usize, h as usize, stride as usize);
487 if w == 0 || h == 0 || w > 4096 || h > 4096 || stride < w * 4 {
488 bail!("video_present: bad geometry {w}x{h} stride {stride}");
489 }
490 let mem = memory(&caller)?;
491 let (data, host) = mem.data_and_store_mut(&mut caller);
492 let src = guest_slice(data, ptr, (stride * (h - 1) + w * 4) as u64)?;
493 let row = w * 4;
494 host.rgba.resize(row * h, 0);
495 if stride == row {
496 host.rgba.copy_from_slice(src);
497 } else {
498 for (y, dst) in host.rgba.chunks_exact_mut(row).enumerate() {
499 dst.copy_from_slice(&src[y * stride..y * stride + row]);
500 }
501 }
502 if host.hashing {
503 host.video_hash.update(&host.rgba);
504 }
505 host.width = w;
506 host.height = h;
507 host.frames_presented += 1;
508 Ok(())
509 },
510 )?;
511
512 linker.func_wrap("gasm", "audio_config", |mut caller: Caller<'_, Host>, rate: u32, channels: u32| {
513 let h = caller.data_mut();
514 if (8000..=192_000).contains(&rate) && (channels == 1 || channels == 2) {
515 h.audio_rate = rate;
516 h.audio_channels = channels;
517 if let Some(a) = &mut h.audio {
518 a.configure(rate, channels);
519 }
520 }
521 })?;
522
523 linker.func_wrap(
524 "gasm",
525 "audio_push",
526 |mut caller: Caller<'_, Host>, ptr: u32, frames: u32| -> wasmtime::Result<()> {
527 let mem = memory(&caller)?;
528 let (data, host) = mem.data_and_store_mut(&mut caller);
529 let len = frames as u64 * host.audio_channels as u64 * 4;
530 let bytes = guest_slice(data, ptr, len)?;
531 if host.hashing {
532 host.audio_hash.update(bytes);
533 }
534 host.audio_frames += frames as u64;
535 if let Some(a) = &mut host.audio {
536 a.push_le_f32(bytes);
537 }
538 Ok(())
539 },
540 )?;
541
542 linker.func_wrap("gasm", "input_pad", |caller: Caller<'_, Host>, player: u32| -> u32 {
543 caller.data().pads.get(player as usize).copied().unwrap_or(0)
544 })?;
545
546 linker.func_wrap(
547 "gasm",
548 "text_input",
549 |mut caller: Caller<'_, Host>, dst: u32, cap: u32| -> wasmtime::Result<i32> {
550 let mem = memory(&caller)?;
551 let (data, host) = mem.data_and_store_mut(&mut caller);
552 let Some(t) = &host.text else { return Ok(-1) };
553 copy_if_fits(data, dst, cap, t.as_bytes())
554 },
555 )?;
556
557 linker.func_wrap("gasm", "input_mode", |mut caller: Caller<'_, Host>, flags: u32| {
558 caller.data_mut().input_mode = flags & 7;
559 })?;
560
561 linker.func_wrap(
562 "gasm",
563 "key_state",
564 |mut caller: Caller<'_, Host>, dst: u32, len: u32| -> wasmtime::Result<i32> {
565 let mem = memory(&caller)?;
566 let (data, host) = mem.data_and_store_mut(&mut caller);
567 let Some(keys) = host.input.keys else { return Ok(-1) };
568 let n = (len as usize).min(KEY_STATE_BYTES);
569 guest_slice_mut(data, dst, n as u64)?.copy_from_slice(&keys[..n]);
570 Ok(KEY_STATE_BYTES as i32)
571 },
572 )?;
573
574 linker.func_wrap(
575 "gasm",
576 "key_events",
577 |mut caller: Caller<'_, Host>, dst: u32, cap: u32| -> wasmtime::Result<i32> {
578 let mem = memory(&caller)?;
579 let (data, host) = mem.data_and_store_mut(&mut caller);
580 if host.input.keys.is_none() {
581 return Ok(-1);
582 }
583 let events = &host.input.key_events;
584 let len = events.len() * 4;
585 if len <= cap as usize {
586 let out = guest_slice_mut(data, dst, len as u64)?;
587 for (b, &(c, d)) in out.chunks_exact_mut(4).zip(events) {
588 let c = c.to_le_bytes();
589 b.copy_from_slice(&[c[0], c[1], d as u8, 0]);
590 }
591 }
592 Ok(len as i32)
593 },
594 )?;
595
596 linker.func_wrap(
597 "gasm",
598 "pointer",
599 |mut caller: Caller<'_, Host>, dst: u32, cap: u32| -> wasmtime::Result<i32> {
600 let mem = memory(&caller)?;
601 let (data, host) = mem.data_and_store_mut(&mut caller);
602 let Some(p) = &host.input.pointer else { return Ok(-1) };
603 if cap as usize >= POINTER_BYTES {
604 let b = pointer_bytes(p, (host.width, host.height), host.aspect);
605 guest_slice_mut(data, dst, POINTER_BYTES as u64)?.copy_from_slice(&b);
606 }
607 Ok(POINTER_BYTES as i32)
608 },
609 )?;
610
611 linker.func_wrap(
612 "gasm",
613 "gamepad",
614 |mut caller: Caller<'_, Host>, slot: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
615 let mem = memory(&caller)?;
616 let (data, host) = mem.data_and_store_mut(&mut caller);
617 let (Some(pads), true) = (&host.input.gamepads, slot < 4) else { return Ok(-1) };
618 if cap as usize >= GAMEPAD_BYTES {
619 let b = gamepad_bytes(&pads[slot as usize]);
620 guest_slice_mut(data, dst, GAMEPAD_BYTES as u64)?.copy_from_slice(&b);
621 }
622 Ok(GAMEPAD_BYTES as i32)
623 },
624 )?;
625
626 linker.func_wrap(
627 "gasm",
628 "gamepad_name",
629 |mut caller: Caller<'_, Host>, slot: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
630 let mem = memory(&caller)?;
631 let (data, host) = mem.data_and_store_mut(&mut caller);
632 let Some(g) = host.input.gamepads.as_ref().and_then(|p| p.get(slot as usize)).filter(|g| g.connected) else { return Ok(-1) };
633 copy_if_fits(data, dst, cap, g.name.as_bytes())
634 },
635 )?;
636
637 linker.func_wrap(
638 "gasm",
639 "param",
640 |mut caller: Caller<'_, Host>, ptr: u32, len: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
641 let name = guest_str(&caller, ptr, len)?;
642 let mem = memory(&caller)?;
643 let (data, host) = mem.data_and_store_mut(&mut caller);
644 let Some(v) = host.params.get(&name) else { return Ok(-1) };
645 copy_if_fits(data, dst, cap, v.as_bytes())
646 },
647 )?;
648
649 fn read_asset(caller: &mut Caller<'_, Host>, ptr: u32, len: u32, offset: u64, dst: u32, cap: u32) -> wasmtime::Result<i32> {
652 let name = guest_str(caller, ptr, len)?;
653 let mem = memory(caller)?;
654 let (data, host) = mem.data_and_store_mut(caller);
655 let Some(asset) = host.assets.get(&name) else { return Ok(-1) };
656 let n = asset.size().saturating_sub(offset).min(cap as u64);
657 let out = guest_slice_mut(data, dst, n)?;
658 Ok(asset.read_at(offset, out) as i32)
659 }
660
661 linker.func_wrap(
662 "gasm",
663 "asset_read_at",
664 |mut caller: Caller<'_, Host>, ptr: u32, len: u32, offset: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
665 read_asset(&mut caller, ptr, len, offset as u64, dst, cap)
666 },
667 )?;
668
669 linker.func_wrap(
670 "gasm",
671 "asset_read_at64",
672 |mut caller: Caller<'_, Host>, ptr: u32, len: u32, offset: u64, dst: u32, cap: u32| -> wasmtime::Result<i32> {
673 read_asset(&mut caller, ptr, len, offset, dst, cap)
674 },
675 )?;
676
677 linker.func_wrap(
678 "gasm",
679 "asset_read",
680 |mut caller: Caller<'_, Host>, ptr: u32, len: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
681 read_asset(&mut caller, ptr, len, 0, dst, cap)
682 },
683 )?;
684
685 linker.func_wrap("gasm", "asset_count", |caller: Caller<'_, Host>| -> u32 { caller.data().assets.names().len() as u32 })?;
686
687 linker.func_wrap(
688 "gasm",
689 "asset_name",
690 |mut caller: Caller<'_, Host>, index: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
691 let mem = memory(&caller)?;
692 let (data, host) = mem.data_and_store_mut(&mut caller);
693 let Some(n) = host.assets.names().get(index as usize) else { return Ok(-1) };
694 copy_if_fits(data, dst, cap, n.as_bytes())
695 },
696 )?;
697
698 linker.func_wrap(
699 "gasm",
700 "asset_size",
701 |caller: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<i32> {
702 let name = guest_str(&caller, ptr, len)?;
703 Ok(match caller.data().assets.size(&name) {
704 None => -1,
705 Some(n) if n > i32::MAX as u64 => -2,
706 Some(n) => n as i32,
707 })
708 },
709 )?;
710
711 linker.func_wrap(
712 "gasm",
713 "asset_size64",
714 |caller: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<i64> {
715 let name = guest_str(&caller, ptr, len)?;
716 Ok(caller.data().assets.size(&name).map_or(-1, |n| n as i64))
717 },
718 )?;
719 Ok(())
720}
721
722fn trap(e: String) -> wasmtime::Error {
723 format_err!("{e}")
724}
725
726fn add_gfx_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
727 const M: &str = "gasm:gfx";
728 linker.func_wrap(M, "width", |c: Caller<'_, Host>| -> u32 { c.data().gfx.size().0 })?;
729 linker.func_wrap(M, "height", |c: Caller<'_, Host>| -> u32 { c.data().gfx.size().1 })?;
730 linker.func_wrap(M, "create_shader", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
731 let src = guest_str(&c, ptr, len)?;
732 c.data_mut().gfx.create_shader(&src).map_err(trap)
733 })?;
734 linker.func_wrap(M, "create_buffer", |mut c: Caller<'_, Host>, size: u32, usage: u32| -> wasmtime::Result<u32> {
735 c.data_mut().gfx.create_buffer(size, usage).map_err(trap)
736 })?;
737 linker.func_wrap(M, "create_pipeline", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
738 let json = guest_str(&c, ptr, len)?;
739 c.data_mut().gfx.create_pipeline(&json).map_err(trap)
740 })?;
741 linker.func_wrap(M, "create_bind_group", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
742 let json = guest_str(&c, ptr, len)?;
743 c.data_mut().gfx.create_bind_group(&json).map_err(trap)
744 })?;
745 linker.func_wrap(
746 M,
747 "write_buffer",
748 |mut c: Caller<'_, Host>, buf: u32, offset: u32, ptr: u32, len: u32| -> wasmtime::Result<()> {
749 let mem = memory(&c)?;
750 let (data, host) = mem.data_and_store_mut(&mut c);
751 let bytes = guest_slice(data, ptr, len as u64)?;
752 host.gfx.write_buffer(buf, offset, bytes).map_err(trap)?;
753 if host.hashing {
754 host.video_hash.update(bytes);
755 }
756 Ok(())
757 },
758 )?;
759 linker.func_wrap(M, "create_bind_group_layout", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
760 let json = guest_str(&c, ptr, len)?;
761 c.data_mut().gfx.create_bind_group_layout(&json).map_err(trap)
762 })?;
763 linker.func_wrap(M, "create_texture", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
764 let json = guest_str(&c, ptr, len)?;
765 c.data_mut().gfx.create_texture(&json).map_err(trap)
766 })?;
767 linker.func_wrap(M, "create_sampler", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
768 let json = guest_str(&c, ptr, len)?;
769 c.data_mut().gfx.create_sampler(&json).map_err(trap)
770 })?;
771 linker.func_wrap(
772 M,
773 "write_texture",
774 |mut c: Caller<'_, Host>, tex: u32, mip: u32, x: u32, y: u32, w: u32, h: u32, ptr: u32, len: u32| -> wasmtime::Result<()> {
775 let mem = memory(&c)?;
776 let (data, host) = mem.data_and_store_mut(&mut c);
777 let bytes = guest_slice(data, ptr, len as u64)?;
778 host.gfx.write_texture(tex, mip, x, y, w, h, bytes).map_err(trap)?;
779 if host.hashing {
780 for v in [tex, mip, x, y, w, h] {
782 host.video_hash.update(&v.to_le_bytes());
783 }
784 host.video_hash.update(bytes);
785 }
786 Ok(())
787 },
788 )?;
789 linker.func_wrap(M, "begin_frame", |mut c: Caller<'_, Host>, r: f32, g: f32, b: f32, a: f32| -> wasmtime::Result<u32> {
790 let h = c.data_mut();
791 let show = h.show_frame;
792 h.gfx.begin_frame([r, g, b, a], show).map(u32::from).map_err(trap)
793 })?;
794 linker.func_wrap(M, "set_pipeline", |mut c: Caller<'_, Host>, p: u32| -> wasmtime::Result<()> {
795 c.data_mut().gfx.set_pipeline(p).map_err(trap)
796 })?;
797 linker.func_wrap(M, "set_bind_group", |mut c: Caller<'_, Host>, i: u32, bg: u32| -> wasmtime::Result<()> {
798 c.data_mut().gfx.set_bind_group(i, bg).map_err(trap)
799 })?;
800 linker.func_wrap(
801 M,
802 "set_bind_group_offsets",
803 |mut c: Caller<'_, Host>, i: u32, bg: u32, ptr: u32, count: u32| -> wasmtime::Result<()> {
804 let mem = memory(&c)?;
805 let (data, host) = mem.data_and_store_mut(&mut c);
806 let bytes = guest_slice(data, ptr, count as u64 * 4)?;
807 let mut offsets = [0u32; 32];
808 if count as usize > offsets.len() {
809 bail!("gfx.set_bind_group_offsets: {count} offsets (a bind group has at most {})", offsets.len());
810 }
811 for (o, b) in offsets.iter_mut().zip(bytes.chunks_exact(4)) {
812 *o = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
813 }
814 host.gfx.set_bind_group_offsets(i, bg, &offsets[..count as usize]).map_err(trap)
815 },
816 )?;
817 linker.func_wrap(
818 M,
819 "set_viewport",
820 |mut c: Caller<'_, Host>, x: f32, y: f32, w: f32, h: f32, min: f32, max: f32| -> wasmtime::Result<()> {
821 c.data_mut().gfx.set_viewport(x, y, w, h, min, max).map_err(trap)
822 },
823 )?;
824 linker.func_wrap(M, "set_scissor_rect", |mut c: Caller<'_, Host>, x: u32, y: u32, w: u32, h: u32| -> wasmtime::Result<()> {
825 c.data_mut().gfx.set_scissor_rect(x, y, w, h).map_err(trap)
826 })?;
827 linker.func_wrap(M, "set_vertex_buffer", |mut c: Caller<'_, Host>, slot: u32, b: u32, off: u32| -> wasmtime::Result<()> {
828 c.data_mut().gfx.set_vertex_buffer(slot, b, off).map_err(trap)
829 })?;
830 linker.func_wrap(M, "set_index_buffer", |mut c: Caller<'_, Host>, b: u32, fmt: u32, off: u32| -> wasmtime::Result<()> {
831 c.data_mut().gfx.set_index_buffer(b, fmt, off).map_err(trap)
832 })?;
833 linker.func_wrap(M, "draw", |mut c: Caller<'_, Host>, vc: u32, ic: u32, fv: u32, fi: u32| -> wasmtime::Result<()> {
834 c.data_mut().gfx.draw(vc, ic, fv, fi).map_err(trap)
835 })?;
836 linker.func_wrap(M, "draw_indexed", |mut c: Caller<'_, Host>, ic: u32, n: u32, first: u32, base: i32, fi: u32| -> wasmtime::Result<()> {
837 c.data_mut().gfx.draw_indexed(ic, n, first, base, fi).map_err(trap)
838 })?;
839 linker.func_wrap(M, "end_frame", |mut c: Caller<'_, Host>| -> wasmtime::Result<()> {
840 let h = c.data_mut();
841 h.frames_presented += 1;
842 h.gfx.end_frame().map_err(trap)
843 })?;
844 linker.func_wrap(M, "destroy", |mut c: Caller<'_, Host>, handle: u32| -> wasmtime::Result<()> {
845 c.data_mut().gfx.destroy(handle).map_err(trap)
846 })?;
847 Ok(())
848}
849
850fn add_net_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
851 const M: &str = "gasm:net";
852 linker.func_wrap(M, "open", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<i32> {
853 let url = guest_str(&c, ptr, len)?;
854 Ok(c.data_mut().net.open(&url))
855 })?;
856 linker.func_wrap(M, "state", |c: Caller<'_, Host>, h: i32| -> wasmtime::Result<u32> { c.data().net.state(h).map_err(trap) })?;
857 linker.func_wrap(M, "send", |mut c: Caller<'_, Host>, h: i32, ptr: u32, len: u32| -> wasmtime::Result<i32> {
858 let mem = memory(&c)?;
859 let msg = guest_slice(mem.data(&c), ptr, len as u64)?.to_vec();
860 if msg.is_empty() {
861 c.data().net.state(h).map_err(trap)?; return Ok(-1);
863 }
864 c.data_mut().net.send(h, msg).map_err(trap)
865 })?;
866 linker.func_wrap(M, "recv", |mut c: Caller<'_, Host>, h: i32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
867 let mem = memory(&c)?;
868 let (data, host) = mem.data_and_store_mut(&mut c);
869 let msg = match host.net.peek(h).map_err(trap)? {
870 Ok(m) => m,
871 Err(code) => return Ok(code),
872 };
873 let n = copy_if_fits(data, dst, cap, msg)?;
874 if n as usize <= cap as usize {
875 host.net.pop(h);
876 }
877 Ok(n)
878 })?;
879 linker.func_wrap(M, "close", |mut c: Caller<'_, Host>, h: i32| -> wasmtime::Result<()> { c.data_mut().net.close(h).map_err(trap) })?;
880 Ok(())
881}
882
883fn add_storage_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
884 const M: &str = "gasm:storage";
885 linker.func_wrap(M, "get", |mut c: Caller<'_, Host>, kp: u32, kl: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
886 let key = guest_str(&c, kp, kl)?;
887 let mem = memory(&c)?;
888 let (data, host) = mem.data_and_store_mut(&mut c);
889 let Some(v) = host.storage.get(&key) else { return Ok(-1) };
890 copy_if_fits(data, dst, cap, v)
891 })?;
892 linker.func_wrap(M, "set", |mut c: Caller<'_, Host>, kp: u32, kl: u32, vp: u32, vl: u32| -> wasmtime::Result<i32> {
893 let key = guest_str(&c, kp, kl)?;
894 let mem = memory(&c)?;
895 let (data, host) = mem.data_and_store_mut(&mut c);
896 let value = guest_slice(data, vp, vl as u64)?;
897 Ok(match host.storage.set(&key, value) {
898 Ok(()) => 0,
899 Err(e) => {
900 eprintln!("[gasm] storage: {key}: {e}");
901 e.code()
902 }
903 })
904 })?;
905 linker.func_wrap(M, "count", |mut c: Caller<'_, Host>| -> u32 { c.data_mut().storage.keys().len() as u32 })?;
906 linker.func_wrap(M, "key", |mut c: Caller<'_, Host>, index: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
907 let mem = memory(&c)?;
908 let (data, host) = mem.data_and_store_mut(&mut c);
909 let Some(k) = host.storage.keys().get(index as usize) else { return Ok(-1) };
910 copy_if_fits(data, dst, cap, k.as_bytes())
911 })?;
912 linker.func_wrap(M, "delete", |mut c: Caller<'_, Host>, kp: u32, kl: u32| -> wasmtime::Result<i32> {
913 let key = guest_str(&c, kp, kl)?;
914 Ok(if c.data_mut().storage.delete(&key) { 0 } else { -1 })
915 })?;
916 Ok(())
917}
918
919#[derive(Debug)]
921pub enum Stop {
922 Exit(i32),
924 Trap(String),
925}
926
927impl std::fmt::Display for Stop {
928 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
929 match self {
930 Stop::Exit(code) => write!(f, "guest exited with code {code}"),
931 Stop::Trap(msg) => write!(f, "guest trapped: {msg}"),
932 }
933 }
934}
935
936impl std::error::Error for Stop {}
937
938fn classify(e: wasmtime::Error) -> Stop {
939 if let Some(exit) = e.downcast_ref::<wasi::Exit>() {
940 return Stop::Exit(exit.0);
941 }
942 if e.downcast_ref::<switching::Quit>().is_some() {
943 return Stop::Exit(0);
944 }
945 if e.downcast_ref::<wasmtime::Trap>() == Some(&wasmtime::Trap::Interrupt) {
946 return Stop::Trap(format!("a guest call ran longer than the time limit (stuck in a loop?); see --call-timeout\n{e:?}"));
947 }
948 Stop::Trap(format!("{e:?}"))
949}
950
951const TICKS_PER_SEC: u64 = 10;
953
954pub fn engine() -> &'static Engine {
959 static ENGINE: OnceLock<Engine> = OnceLock::new();
960 ENGINE.get_or_init(new_engine)
961}
962
963fn new_engine() -> Engine {
964 let mut config = Config::new();
965 config.epoch_interruption(true);
966 config.async_stack_size(4 << 20);
968 let engine = Engine::new(&config).expect("wasmtime engine");
969 let ticker = engine.clone();
970 std::thread::Builder::new()
971 .name("gasm-epoch".into())
972 .spawn(move || {
973 loop {
974 std::thread::sleep(Duration::from_millis(1000 / TICKS_PER_SEC));
975 ticker.increment_epoch();
976 }
977 })
978 .expect("epoch thread");
979 engine
980}
981
982pub fn precompile(wasm: &[u8]) -> wasmtime::Result<Vec<u8>> {
984 engine().precompile_module(wasm)
985}
986
987#[derive(Clone, Copy)]
989pub struct LoadOptions {
990 pub allow_precompiled: bool,
993 pub call_timeout: Option<Duration>,
995 pub stack_switching: bool,
998}
999
1000impl Default for LoadOptions {
1001 fn default() -> Self {
1002 LoadOptions { allow_precompiled: false, call_timeout: Some(Duration::from_secs(30)), stack_switching: true }
1003 }
1004}
1005
1006type Running = Pin<Box<dyn Future<Output = (Store<Host>, wasmtime::Result<i32>)>>>;
1008
1009pub struct Game {
1013 store: Option<Store<Host>>,
1015 frame: TypedFunc<(), ()>,
1016 exit: Option<TypedFunc<(), ()>>,
1017 deadline: u64,
1018 run: Option<TypedFunc<(), i32>>,
1020 running: Option<Running>,
1021 exchange: Option<Arc<Exchange>>,
1022 ended: bool,
1024 gl: bool,
1026}
1027
1028impl Game {
1029 pub fn load(wasm: &[u8], host: Host, opts: LoadOptions) -> Result<Game, Stop> {
1030 Self::load_inner(wasm, host, opts).map_err(classify)
1031 }
1032
1033 fn load_inner(wasm: &[u8], host: Host, opts: LoadOptions) -> wasmtime::Result<Game> {
1034 let module = if wasm.starts_with(b"\0asm") {
1035 Module::new(engine(), wasm)?
1036 } else if opts.allow_precompiled {
1037 unsafe { Module::deserialize(engine(), wasm)? }
1040 } else {
1041 bail!("not a wasm module (a precompiled .cwasm runs as native code: pass --allow-precompiled if you made it yourself)");
1042 };
1043 let gl = module.imports().any(|i| i.module() == "gasm:gl");
1044 if gl && module.imports().any(|i| i.module() == "gasm:gfx") {
1045 bail!("a module imports gasm:gfx or gasm:gl, not both");
1046 }
1047 let has_run = module.get_export("gasm_run").is_some();
1049 let switching = has_run && opts.stack_switching;
1050 if has_run && !switching && module.imports().any(|i| i.module() == "asyncify") {
1051 bail!("this module is a run build (no Asyncify): it needs stack switching (gasm_run); use the game's Asyncify build");
1053 }
1054 let engine = engine();
1055 let mut linker: Linker<Host> = Linker::new(engine);
1056 add_gasm_imports(&mut linker)?;
1057 if switching {
1058 switching::add_yield_async(&mut linker)?;
1059 } else {
1060 switching::add_yield_sync(&mut linker)?;
1061 }
1062 add_gfx_imports(&mut linker)?;
1063 crate::gl::add_gl_imports(&mut linker)?;
1064 add_net_imports(&mut linker)?;
1065 add_storage_imports(&mut linker)?;
1066 let mut store = Store::new(engine, host);
1067 let mut provided = HashSet::new();
1069 for (m, f, _) in linker.iter(&mut store) {
1070 provided.insert(m.to_owned());
1071 provided.insert(format!("{m}.{f}"));
1072 }
1073 for f in wasi::IMPLEMENTED {
1074 provided.insert(format!("{}.{f}", wasi::MODULE));
1075 }
1076 provided.insert(wasi::MODULE.to_owned());
1077 store.data_mut().provided = provided;
1078 wasi::add_to_linker(&mut linker, &module)?;
1079 linker.define_unknown_imports_as_traps(&module)?;
1082
1083 let deadline = opts.call_timeout.map_or(u64::MAX / 2, |t| (t.as_millis() as u64 * TICKS_PER_SEC).div_ceil(1000).max(1));
1084 store.epoch_deadline_trap();
1085 store.set_epoch_deadline(deadline);
1086 let exchange = switching.then(|| Exchange::new(deadline));
1087 store.data_mut().run = exchange.clone();
1088 let instance: Instance = if switching {
1089 switching::block_on(linker.instantiate_async(&mut store, &module))??
1090 } else {
1091 linker.instantiate(&mut store, &module)?
1092 };
1093 let memory = instance
1094 .get_memory(&mut store, "memory")
1095 .ok_or_else(|| format_err!("guest does not export `memory`"))?;
1096 store.data_mut().memory = Some(memory);
1097
1098 fn call<R: wasmtime::WasmResults + Send + Sync>(store: &mut Store<Host>, f: TypedFunc<(), R>, switching: bool) -> wasmtime::Result<R> {
1100 if switching { switching::block_on(f.call_async(store, ()))? } else { f.call(store, ()) }
1101 }
1102 if let Ok(init) = instance.get_typed_func::<(), ()>(&mut store, "_initialize") {
1103 store.set_epoch_deadline(deadline);
1104 call(&mut store, init, switching)?;
1105 }
1106 let version = instance.get_typed_func::<(), i32>(&mut store, "gasm_abi_version")?;
1107 let version = call(&mut store, version, switching)?;
1108 if version != ABI_VERSION {
1109 bail!("guest targets gasm ABI v{version}, runner implements v{ABI_VERSION}");
1110 }
1111 store.set_epoch_deadline(deadline);
1112 let init = instance.get_typed_func::<(), i32>(&mut store, "gasm_init")?;
1113 let rc = call(&mut store, init, switching)?;
1114 if rc != 0 {
1115 bail!("gasm_init failed with code {rc}");
1116 }
1117 let frame = instance.get_typed_func::<(), ()>(&mut store, "gasm_frame")?;
1118 let exit = instance.get_typed_func::<(), ()>(&mut store, "gasm_exit").ok();
1119 let run = if switching { Some(instance.get_typed_func::<(), i32>(&mut store, "gasm_run")?) } else { None };
1120 Ok(Game { store: Some(store), frame, exit, deadline, run, running: None, exchange, ended: false, gl })
1121 }
1122
1123 pub fn uses_gl(&self) -> bool {
1125 self.gl
1126 }
1127
1128 pub fn switching(&self) -> bool {
1130 self.run.is_some()
1131 }
1132
1133 pub fn frame(&mut self) -> Result<(), Stop> {
1135 if self.ended {
1136 return Err(Stop::Trap("the guest is not running".into()));
1137 }
1138 let Some(run) = self.run.clone() else {
1139 let store = self.store.as_mut().expect("store");
1140 store.set_epoch_deadline(self.deadline);
1141 let r = self.frame.call(&mut *store, ()).map_err(classify);
1142 store.data_mut().frame_index += 1;
1143 self.ended = r.is_err();
1144 return r;
1145 };
1146 match &self.exchange {
1147 Some(ex) if self.running.is_some() => ex.set(Cmd::Resume),
1148 _ => {
1149 let mut store = self.store.take().expect("store");
1151 store.set_epoch_deadline(self.deadline);
1152 self.running = Some(Box::pin(async move {
1153 let r = run.call_async(&mut store, ()).await;
1154 (store, r)
1155 }));
1156 }
1157 }
1158 self.poll()
1159 }
1160
1161 fn poll(&mut self) -> Result<(), Stop> {
1163 let Some(running) = self.running.as_mut() else { return Ok(()) };
1164 match switching::poll_once(running.as_mut()) {
1165 Poll::Pending => Ok(()),
1166 Poll::Ready((store, r)) => {
1167 self.store = Some(store);
1168 self.running = None;
1169 self.ended = true;
1170 Err(match r {
1171 Ok(code) => Stop::Exit(code),
1172 Err(e) => classify(e),
1173 })
1174 }
1175 }
1176 }
1177
1178 pub fn exit(&mut self) {
1181 if self.running.is_some() {
1182 if let Some(ex) = &self.exchange {
1183 ex.set(Cmd::Exit);
1184 }
1185 if let Err(Stop::Trap(t)) = self.poll() {
1186 eprintln!("[gasm] gasm_exit trapped: {t}");
1187 }
1188 if self.running.is_some() {
1189 self.running = None;
1191 }
1192 self.exit = None;
1193 return;
1194 }
1195 if let (Some(f), Some(store)) = (self.exit.take(), self.store.as_mut()) {
1196 store.set_epoch_deadline(self.deadline);
1197 let r = if self.run.is_some() { switching::block_on(f.call_async(&mut *store, ())).and_then(|r| r) } else { f.call(&mut *store, ()) };
1198 if let Err(e) = r {
1199 if let Stop::Trap(t) = classify(e) {
1200 eprintln!("[gasm] gasm_exit trapped: {t}");
1201 }
1202 }
1203 }
1204 }
1205
1206 pub fn with_host<R>(&mut self, f: impl FnOnce(&mut Host) -> R) -> R {
1210 if let Some(store) = &mut self.store {
1211 return f(store.data_mut());
1212 }
1213 let (Some(running), Some(ex)) = (self.running.as_mut(), &self.exchange) else {
1214 panic!("with_host: the guest's store is gone (gasm_exit yielded)");
1215 };
1216 let mut f = Some(f);
1217 let mut out = None;
1218 let mut job = |h: &mut Host| out = Some((f.take().expect("job runs once"))(h));
1219 let ptr: *mut (dyn FnMut(&mut Host) + '_) = &mut job;
1220 let ptr: *mut (dyn FnMut(&mut Host) + 'static) = unsafe { std::mem::transmute(ptr) };
1223 ex.set(Cmd::Job(Job(ptr)));
1224 let polled = switching::poll_once(running.as_mut());
1225 ex.set(Cmd::None);
1226 match polled {
1227 Poll::Pending => {}
1228 Poll::Ready(_) => unreachable!("yield_frame stays suspended after a job"),
1229 }
1230 out.expect("yield_frame ran the job")
1231 }
1232
1233 pub fn host(&self) -> &Host {
1237 self.store.as_ref().expect("Game::host: a gasm_run guest is running; use Game::with_host").data()
1238 }
1239
1240 pub fn host_mut(&mut self) -> &mut Host {
1241 self.store.as_mut().expect("Game::host_mut: a gasm_run guest is running; use Game::with_host").data_mut()
1242 }
1243}
1244
1245#[cfg(test)]
1246mod tests {
1247 use super::*;
1248
1249 #[test]
1250 fn titles_are_cleaned_and_cut() {
1251 assert_eq!(clean_title("A\u{7}B\u{202e}C\u{2069}").as_deref(), Some("ABC"));
1252 assert_eq!(clean_title("\n\t"), None);
1253 assert_eq!(clean_title(&"é".repeat(200)).map(|t| t.len()), Some(256));
1255 }
1256
1257 const RUN_GUEST: &str = r#"(module
1258 (import "gasm" "yield_frame" (func $yield))
1259 (memory (export "memory") 1)
1260 (global $n (mut i32) (i32.const 0))
1261 (func (export "gasm_abi_version") (result i32) i32.const 0)
1262 (func (export "gasm_init") (result i32) i32.const 0)
1263 (func (export "gasm_frame") call $yield)
1264 (func (export "gasm_exit") (global.set $n (i32.const 100)))
1265 (func (export "frames") (result i32) global.get $n)
1266 (func (export "gasm_run") (result i32)
1267 (loop $l
1268 (global.set $n (i32.add (global.get $n) (i32.const 1)))
1269 call $yield
1270 (br_if $l (i32.lt_u (global.get $n) (i32.const 3))))
1271 i32.const 7))"#;
1272
1273 fn host() -> Host {
1274 Host::new(Assets::new(), HashMap::new(), None, Gfx::null(), Net::new(false), Storage::memory())
1275 }
1276
1277 #[test]
1278 fn gasm_run_guests_suspend_between_frames() {
1279 let mut g = Game::load(&wat::parse_str(RUN_GUEST).unwrap(), host(), LoadOptions::default()).unwrap();
1280 assert!(g.switching());
1281 g.with_host(|h| h.frame_rate = 30.0); assert!(g.frame().is_ok()); assert_eq!(g.with_host(|h| h.frame_rate), 30.0);
1285 assert!(g.frame().is_ok()); assert!(g.frame().is_ok()); assert!(matches!(g.frame(), Err(Stop::Exit(7))));
1289 assert!(g.frame().is_err(), "never called again");
1290 }
1291
1292 #[test]
1293 fn exit_runs_on_top_of_a_suspended_run() {
1294 let mut g = Game::load(&wat::parse_str(RUN_GUEST).unwrap(), host(), LoadOptions::default()).unwrap();
1295 g.frame().unwrap();
1296 g.exit();
1297 assert!(g.store.is_some());
1299 }
1300
1301 #[test]
1302 fn yield_frame_outside_gasm_run_traps() {
1303 let opts = LoadOptions { stack_switching: false, ..LoadOptions::default() };
1304 let mut g = Game::load(&wat::parse_str(RUN_GUEST).unwrap(), host(), opts).unwrap();
1305 assert!(!g.switching());
1306 match g.frame() {
1307 Err(Stop::Trap(t)) => assert!(t.contains("only inside gasm_run"), "{t}"),
1308 other => panic!("expected a trap, got {:?}", other.err()),
1309 }
1310 }
1311
1312 #[test]
1313 fn custom_sections_are_found() {
1314 let mut wasm = b"\0asm\x01\0\0\0\x01\x01\0".to_vec();
1316 wasm.extend_from_slice(&[0, 14, 10]);
1317 wasm.extend_from_slice(b"gasm.titleHi\0");
1318 assert_eq!(custom_section(&wasm, "gasm.title"), Some(&b"Hi\0"[..]));
1319 assert_eq!(static_title(&wasm).as_deref(), Some("Hi"));
1320 assert_eq!(custom_section(&wasm, "other"), None);
1321 assert_eq!(custom_section(&wasm[..wasm.len() - 2], "gasm.title"), None); assert_eq!(custom_section(b"not wasm", "gasm.title"), None);
1323 }
1324}