1use std::collections::HashMap;
5use std::time::Instant;
6
7use wasmtime::{Caller, Engine, Instance, Linker, Memory, Module, Store, TypedFunc, bail, format_err};
8use wasmtime_wasi::WasiCtx;
9use wasmtime_wasi::p1::{self, WasiP1Ctx};
10
11use crate::audio::AudioSink;
12use crate::gfx::Gfx;
13use crate::net::Net;
14use crate::storage::Storage;
15
16pub const ABI_VERSION: i32 = 0;
17
18#[derive(Clone, Copy)]
20pub struct Fnv(pub u32);
21
22impl Fnv {
23 pub fn new() -> Self {
24 Fnv(0x811c_9dc5)
25 }
26 pub fn update(&mut self, bytes: &[u8]) {
27 let mut h = self.0;
28 for &b in bytes {
29 h ^= b as u32;
30 h = h.wrapping_mul(0x0100_0193);
31 }
32 self.0 = h;
33 }
34}
35
36pub struct Host {
37 wasi: WasiP1Ctx,
38 memory: Option<Memory>,
39 start: Instant,
40 pub virtual_time_ms: Option<f64>,
42 pub frame_rate: f64,
43 pub pads: [u32; 4],
44 pub assets: HashMap<String, Vec<u8>>,
45 pub params: HashMap<String, String>,
46 pub audio: Option<AudioSink>,
47 pub gfx: Gfx,
48 pub net: Net,
49 pub storage: Storage,
50 pub show_frame: bool,
52 audio_rate: u32,
53 audio_channels: u32,
54 pub rgba: Vec<u8>,
56 pub width: usize,
57 pub height: usize,
58 pub frames_presented: u64,
59 pub hashing: bool,
60 pub video_hash: Fnv,
61 pub audio_hash: Fnv,
62 pub audio_frames: u64,
63}
64
65impl Host {
66 pub fn new(
67 assets: HashMap<String, Vec<u8>>,
68 params: HashMap<String, String>,
69 audio: Option<AudioSink>,
70 gfx: Gfx,
71 net: Net,
72 storage: Storage,
73 ) -> Self {
74 let wasi = WasiCtx::builder().inherit_stdout().inherit_stderr().build_p1();
75 Host {
76 wasi,
77 memory: None,
78 start: Instant::now(),
79 virtual_time_ms: None,
80 frame_rate: 60.0,
81 pads: [0; 4],
82 assets,
83 params,
84 audio,
85 gfx,
86 net,
87 storage,
88 show_frame: true,
89 audio_rate: 44100,
90 audio_channels: 2,
91 rgba: Vec::new(),
92 width: 0,
93 height: 0,
94 frames_presented: 0,
95 hashing: true,
96 video_hash: Fnv::new(),
97 audio_hash: Fnv::new(),
98 audio_frames: 0,
99 }
100 }
101}
102
103fn guest_slice<'a>(mem: &'a [u8], ptr: u32, len: u64) -> wasmtime::Result<&'a [u8]> {
105 let start = ptr as u64;
106 let end = start.checked_add(len).ok_or_else(|| format_err!("guest pointer overflow"))?;
107 if end > mem.len() as u64 {
108 bail!("guest access out of bounds: {start:#x}..{end:#x} (memory is {:#x})", mem.len());
109 }
110 Ok(&mem[start as usize..end as usize])
111}
112
113fn memory(caller: &Caller<'_, Host>) -> wasmtime::Result<Memory> {
114 caller.data().memory.ok_or_else(|| format_err!("guest memory not yet available"))
115}
116
117fn guest_str(caller: &Caller<'_, Host>, ptr: u32, len: u32) -> wasmtime::Result<String> {
118 let mem = memory(caller)?;
119 let bytes = guest_slice(mem.data(caller), ptr, len as u64)?;
120 Ok(String::from_utf8_lossy(bytes).into_owned())
121}
122
123fn add_gasm_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
124 linker.func_wrap("gasm", "log", |caller: Caller<'_, Host>, ptr: u32, len: u32| {
125 let msg = guest_str(&caller, ptr, len)?;
126 eprintln!("[guest] {msg}");
127 Ok(())
128 })?;
129
130 linker.func_wrap("gasm", "time_ms", |caller: Caller<'_, Host>| -> f64 {
131 let h = caller.data();
132 h.virtual_time_ms.unwrap_or_else(|| h.start.elapsed().as_secs_f64() * 1000.0)
133 })?;
134
135 linker.func_wrap("gasm", "set_frame_rate", |mut caller: Caller<'_, Host>, hz: f64| {
136 if hz.is_finite() && (1.0..=1000.0).contains(&hz) {
137 caller.data_mut().frame_rate = hz;
138 }
139 })?;
140
141 linker.func_wrap(
142 "gasm",
143 "video_present",
144 |mut caller: Caller<'_, Host>, ptr: u32, w: u32, h: u32, stride: u32| -> wasmtime::Result<()> {
145 let (w, h, stride) = (w as usize, h as usize, stride as usize);
146 if w == 0 || h == 0 || w > 4096 || h > 4096 || stride < w * 4 {
147 bail!("video_present: bad geometry {w}x{h} stride {stride}");
148 }
149 let mem = memory(&caller)?;
150 let (data, host) = mem.data_and_store_mut(&mut caller);
151 let src = guest_slice(data, ptr, (stride * (h - 1) + w * 4) as u64)?;
152 host.rgba.resize(w * h * 4, 0);
153 for y in 0..h {
154 let row = &src[y * stride..y * stride + w * 4];
155 host.rgba[y * w * 4..(y + 1) * w * 4].copy_from_slice(row);
156 }
157 if host.hashing {
158 host.video_hash.update(&host.rgba);
159 }
160 host.width = w;
161 host.height = h;
162 host.frames_presented += 1;
163 Ok(())
164 },
165 )?;
166
167 linker.func_wrap("gasm", "audio_config", |mut caller: Caller<'_, Host>, rate: u32, channels: u32| {
168 let h = caller.data_mut();
169 if (8000..=192_000).contains(&rate) && (channels == 1 || channels == 2) {
170 h.audio_rate = rate;
171 h.audio_channels = channels;
172 if let Some(a) = &mut h.audio {
173 a.configure(rate, channels);
174 }
175 }
176 })?;
177
178 linker.func_wrap(
179 "gasm",
180 "audio_push",
181 |mut caller: Caller<'_, Host>, ptr: u32, frames: u32| -> wasmtime::Result<()> {
182 let mem = memory(&caller)?;
183 let (data, host) = mem.data_and_store_mut(&mut caller);
184 let len = frames as u64 * host.audio_channels as u64 * 4;
185 let bytes = guest_slice(data, ptr, len)?;
186 if host.hashing {
187 host.audio_hash.update(bytes);
188 }
189 host.audio_frames += frames as u64;
190 if let Some(a) = &mut host.audio {
191 a.push_le_f32(bytes);
192 }
193 Ok(())
194 },
195 )?;
196
197 linker.func_wrap("gasm", "input_pad", |caller: Caller<'_, Host>, player: u32| -> u32 {
198 caller.data().pads.get(player as usize).copied().unwrap_or(0)
199 })?;
200
201 linker.func_wrap(
202 "gasm",
203 "param",
204 |mut caller: Caller<'_, Host>, ptr: u32, len: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
205 let name = guest_str(&caller, ptr, len)?;
206 let mem = memory(&caller)?;
207 let (data, host) = mem.data_and_store_mut(&mut caller);
208 let Some(v) = host.params.get(&name) else { return Ok(-1) };
209 let v = v.as_bytes();
210 if v.len() <= cap as usize {
211 guest_slice(data, dst, v.len() as u64)?;
212 data[dst as usize..dst as usize + v.len()].copy_from_slice(v);
213 }
214 Ok(v.len() as i32)
215 },
216 )?;
217
218 linker.func_wrap(
219 "gasm",
220 "asset_read_at",
221 |mut caller: Caller<'_, Host>, ptr: u32, len: u32, offset: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
222 let name = guest_str(&caller, ptr, len)?;
223 let mem = memory(&caller)?;
224 let (data, host) = mem.data_and_store_mut(&mut caller);
225 let Some(asset) = host.assets.get(&name) else { return Ok(-1) };
226 let start = (offset as usize).min(asset.len());
227 let n = (asset.len() - start).min(cap as usize);
228 guest_slice(data, dst, n as u64)?;
229 data[dst as usize..dst as usize + n].copy_from_slice(&asset[start..start + n]);
230 Ok(n as i32)
231 },
232 )?;
233
234 linker.func_wrap(
235 "gasm",
236 "asset_size",
237 |caller: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<i32> {
238 let name = guest_str(&caller, ptr, len)?;
239 Ok(caller.data().assets.get(&name).map_or(-1, |a| a.len() as i32))
240 },
241 )?;
242
243 linker.func_wrap(
244 "gasm",
245 "asset_read",
246 |mut caller: Caller<'_, Host>, ptr: u32, len: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
247 let name = guest_str(&caller, ptr, len)?;
248 let mem = memory(&caller)?;
249 let (data, host) = mem.data_and_store_mut(&mut caller);
250 let Some(asset) = host.assets.get(&name) else { return Ok(-1) };
251 let n = asset.len().min(cap as usize);
252 guest_slice(data, dst, n as u64)?; data[dst as usize..dst as usize + n].copy_from_slice(&asset[..n]);
254 Ok(n as i32)
255 },
256 )?;
257 Ok(())
258}
259
260pub fn precompile(wasm: &[u8]) -> wasmtime::Result<Vec<u8>> {
262 Engine::default().precompile_module(wasm)
263}
264
265fn trap(e: String) -> wasmtime::Error {
266 format_err!("{e}")
267}
268
269fn add_gfx_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
270 const M: &str = "gasm:gfx";
271 linker.func_wrap(M, "width", |c: Caller<'_, Host>| c.data().gfx.size().0)?;
272 linker.func_wrap(M, "height", |c: Caller<'_, Host>| c.data().gfx.size().1)?;
273 linker.func_wrap(M, "create_shader", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
274 let src = guest_str(&c, ptr, len)?;
275 c.data_mut().gfx.create_shader(&src).map_err(trap)
276 })?;
277 linker.func_wrap(M, "create_buffer", |mut c: Caller<'_, Host>, size: u32, usage: u32| -> wasmtime::Result<u32> {
278 c.data_mut().gfx.create_buffer(size, usage).map_err(trap)
279 })?;
280 linker.func_wrap(M, "create_pipeline", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
281 let json = guest_str(&c, ptr, len)?;
282 c.data_mut().gfx.create_pipeline(&json).map_err(trap)
283 })?;
284 linker.func_wrap(M, "create_bind_group", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<u32> {
285 let json = guest_str(&c, ptr, len)?;
286 c.data_mut().gfx.create_bind_group(&json).map_err(trap)
287 })?;
288 linker.func_wrap(
289 M,
290 "write_buffer",
291 |mut c: Caller<'_, Host>, buf: u32, offset: u32, ptr: u32, len: u32| -> wasmtime::Result<()> {
292 let mem = memory(&c)?;
293 let (data, host) = mem.data_and_store_mut(&mut c);
294 let bytes = guest_slice(data, ptr, len as u64)?;
295 if host.hashing {
296 host.video_hash.update(bytes);
297 }
298 host.gfx.write_buffer(buf, offset, bytes).map_err(trap)
299 },
300 )?;
301 linker.func_wrap(M, "begin_frame", |mut c: Caller<'_, Host>, r: f32, g: f32, b: f32, a: f32| -> wasmtime::Result<u32> {
302 let h = c.data_mut();
303 let show = h.show_frame;
304 h.gfx.begin_frame([r, g, b, a], show).map(u32::from).map_err(trap)
305 })?;
306 linker.func_wrap(M, "set_pipeline", |mut c: Caller<'_, Host>, p: u32| -> wasmtime::Result<()> {
307 c.data_mut().gfx.set_pipeline(p).map_err(trap)
308 })?;
309 linker.func_wrap(M, "set_bind_group", |mut c: Caller<'_, Host>, i: u32, bg: u32| -> wasmtime::Result<()> {
310 c.data_mut().gfx.set_bind_group(i, bg).map_err(trap)
311 })?;
312 linker.func_wrap(M, "set_vertex_buffer", |mut c: Caller<'_, Host>, slot: u32, b: u32, off: u32| -> wasmtime::Result<()> {
313 c.data_mut().gfx.set_vertex_buffer(slot, b, off).map_err(trap)
314 })?;
315 linker.func_wrap(M, "set_index_buffer", |mut c: Caller<'_, Host>, b: u32, fmt: u32, off: u32| -> wasmtime::Result<()> {
316 c.data_mut().gfx.set_index_buffer(b, fmt, off).map_err(trap)
317 })?;
318 linker.func_wrap(M, "draw", |mut c: Caller<'_, Host>, vc: u32, ic: u32, fv: u32, fi: u32| {
319 c.data_mut().gfx.draw(vc, ic, fv, fi)
320 })?;
321 linker.func_wrap(M, "draw_indexed", |mut c: Caller<'_, Host>, ic: u32, n: u32, first: u32, base: i32, fi: u32| {
322 c.data_mut().gfx.draw_indexed(ic, n, first, base, fi)
323 })?;
324 linker.func_wrap(M, "end_frame", |mut c: Caller<'_, Host>| -> wasmtime::Result<()> {
325 let h = c.data_mut();
326 h.frames_presented += 1;
327 h.gfx.end_frame().map_err(trap)
328 })?;
329 Ok(())
330}
331
332fn add_net_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
333 const M: &str = "gasm:net";
334 linker.func_wrap(M, "open", |mut c: Caller<'_, Host>, ptr: u32, len: u32| -> wasmtime::Result<i32> {
335 let url = guest_str(&c, ptr, len)?;
336 Ok(c.data_mut().net.open(&url))
337 })?;
338 linker.func_wrap(M, "state", |c: Caller<'_, Host>, h: i32| c.data().net.state(h))?;
339 linker.func_wrap(M, "send", |mut c: Caller<'_, Host>, h: i32, ptr: u32, len: u32| -> wasmtime::Result<i32> {
340 if len == 0 {
341 return Ok(-1);
342 }
343 let mem = memory(&c)?;
344 let msg = guest_slice(mem.data(&c), ptr, len as u64)?.to_vec();
345 Ok(c.data_mut().net.send(h, msg))
346 })?;
347 linker.func_wrap(M, "recv", |mut c: Caller<'_, Host>, h: i32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
348 let mem = memory(&c)?;
349 let (data, host) = mem.data_and_store_mut(&mut c);
350 let msg = match host.net.peek(h) {
351 Ok(m) => m,
352 Err(code) => return Ok(code),
353 };
354 let n = msg.len();
355 if n <= cap as usize {
356 guest_slice(data, dst, n as u64)?;
357 data[dst as usize..dst as usize + n].copy_from_slice(msg);
358 host.net.pop(h);
359 }
360 Ok(n as i32)
361 })?;
362 linker.func_wrap(M, "close", |mut c: Caller<'_, Host>, h: i32| c.data_mut().net.close(h))?;
363 Ok(())
364}
365
366fn add_storage_imports(linker: &mut Linker<Host>) -> wasmtime::Result<()> {
367 const M: &str = "gasm:storage";
368 linker.func_wrap(M, "get", |mut c: Caller<'_, Host>, kp: u32, kl: u32, dst: u32, cap: u32| -> wasmtime::Result<i32> {
369 let key = guest_str(&c, kp, kl)?;
370 let mem = memory(&c)?;
371 let (data, host) = mem.data_and_store_mut(&mut c);
372 let Some(v) = host.storage.get(&key) else { return Ok(-1) };
373 if v.len() <= cap as usize {
374 guest_slice(data, dst, v.len() as u64)?;
375 data[dst as usize..dst as usize + v.len()].copy_from_slice(v);
376 }
377 Ok(v.len() as i32)
378 })?;
379 linker.func_wrap(M, "set", |mut c: Caller<'_, Host>, kp: u32, kl: u32, vp: u32, vl: u32| -> wasmtime::Result<i32> {
380 let key = guest_str(&c, kp, kl)?;
381 let mem = memory(&c)?;
382 let (data, host) = mem.data_and_store_mut(&mut c);
383 let value = guest_slice(data, vp, vl as u64)?;
384 Ok(match host.storage.set(&key, value) {
385 Ok(()) => 0,
386 Err(e) => {
387 eprintln!("[gasm] storage: {e}");
388 -1
389 }
390 })
391 })?;
392 linker.func_wrap(M, "delete", |mut c: Caller<'_, Host>, kp: u32, kl: u32| -> wasmtime::Result<i32> {
393 let key = guest_str(&c, kp, kl)?;
394 Ok(if c.data_mut().storage.delete(&key) { 0 } else { -1 })
395 })?;
396 Ok(())
397}
398
399#[derive(Debug)]
401pub enum Stop {
402 Exit(i32),
404 Trap(String),
405}
406
407impl std::fmt::Display for Stop {
408 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409 match self {
410 Stop::Exit(code) => write!(f, "guest exited with code {code}"),
411 Stop::Trap(msg) => write!(f, "guest trapped: {msg}"),
412 }
413 }
414}
415
416impl std::error::Error for Stop {}
417
418fn classify(e: wasmtime::Error) -> Stop {
419 match e.downcast_ref::<wasmtime_wasi::I32Exit>() {
420 Some(exit) => Stop::Exit(exit.0),
421 None => Stop::Trap(format!("{e:?}")),
422 }
423}
424
425pub struct Game {
426 pub store: Store<Host>,
427 frame: TypedFunc<(), ()>,
428 exit: Option<TypedFunc<(), ()>>,
429}
430
431impl Game {
432 pub fn load(wasm: &[u8], host: Host) -> Result<Game, Stop> {
433 Self::load_inner(wasm, host).map_err(classify)
434 }
435
436 fn load_inner(wasm: &[u8], host: Host) -> wasmtime::Result<Game> {
437 let engine = Engine::default();
438 let module = if wasm.starts_with(b"\0asm") {
439 Module::new(&engine, wasm)?
440 } else {
441 unsafe { Module::deserialize(&engine, wasm)? }
444 };
445 let mut linker: Linker<Host> = Linker::new(&engine);
446 p1::add_to_linker_sync(&mut linker, |h: &mut Host| &mut h.wasi)?;
447 add_gasm_imports(&mut linker)?;
448 add_gfx_imports(&mut linker)?;
449 add_net_imports(&mut linker)?;
450 add_storage_imports(&mut linker)?;
451 linker.define_unknown_imports_as_traps(&module)?;
454
455 let mut store = Store::new(&engine, host);
456 let instance: Instance = linker.instantiate(&mut store, &module)?;
457 let memory = instance
458 .get_memory(&mut store, "memory")
459 .ok_or_else(|| format_err!("guest does not export `memory`"))?;
460 store.data_mut().memory = Some(memory);
461
462 if let Ok(init) = instance.get_typed_func::<(), ()>(&mut store, "_initialize") {
463 init.call(&mut store, ())?;
464 }
465 let version = instance
466 .get_typed_func::<(), i32>(&mut store, "gasm_abi_version")?
467 .call(&mut store, ())?;
468 if version != ABI_VERSION {
469 bail!("guest targets gasm ABI v{version}, runner implements v{ABI_VERSION}");
470 }
471 let rc = instance.get_typed_func::<(), i32>(&mut store, "gasm_init")?.call(&mut store, ())?;
472 if rc != 0 {
473 bail!("gasm_init failed with code {rc}");
474 }
475 let frame = instance.get_typed_func::<(), ()>(&mut store, "gasm_frame")?;
476 let exit = instance.get_typed_func::<(), ()>(&mut store, "gasm_exit").ok();
477 Ok(Game { store, frame, exit })
478 }
479
480 pub fn frame(&mut self) -> Result<(), Stop> {
481 self.frame.call(&mut self.store, ()).map_err(classify)
482 }
483
484 pub fn exit(&mut self) {
486 if let Some(f) = self.exit.take() {
487 if let Err(e) = f.call(&mut self.store, ()) {
488 if let Stop::Trap(t) = classify(e) {
489 eprintln!("[gasm] gasm_exit trapped: {t}");
490 }
491 }
492 }
493 }
494
495 pub fn host(&self) -> &Host {
496 self.store.data()
497 }
498
499 pub fn host_mut(&mut self) -> &mut Host {
500 self.store.data_mut()
501 }
502}