Skip to main content

gasm/
native.rs

1//! In-process stub host for running a guest natively (non-wasm targets).
2//!
3//! It implements the same ABI as the runners' headless mode: no display or
4//! audio, virtual time, in-memory storage, and FNV-1a hashes over presented
5//! frames, audio and gfx uploads. It checks arguments like the runners do
6//! (frame rate, audio format, frame geometry, storage keys and limits, gfx
7//! handles and buffer ranges) and panics where a runner would trap. A harness
8//! sets assets/params/input, calls the guest's `gasm_init`/`gasm_frame`, then
9//! reads [`stats`]. Hashes match `gasm-run --headless` for deterministic guests.
10//!
11//! The state is process-wide: run one guest per process (or per test binary
12//! with `--test-threads=1`).
13
14use std::collections::BTreeMap;
15use std::sync::Mutex;
16
17struct State {
18    frame_rate: f64,
19    frames: u64,
20    clock: (f64, u64, f64),
21    now_ms: f64,
22    /// sorted by name (UTF-8 bytes)
23    assets: BTreeMap<String, Vec<u8>>,
24    params: BTreeMap<String, String>,
25    storage: BTreeMap<String, Vec<u8>>,
26    storage_used: usize,
27    /// gasm:files saves so far (handles 1..=saves)
28    saves: u32,
29    pads: [u32; 4],
30    text: String,
31    input_mode: u32,
32    channels: u32,
33    hashing: bool,
34    video_hash: u32,
35    audio_hash: u32,
36    presented: u64,
37    size: (u32, u32),
38    audio_frames: u64,
39    /// gfx objects: Some(buffer size) for buffers, None for other kinds, in creation order
40    gfx: Vec<GfxObj>,
41}
42
43#[derive(Clone, Copy, PartialEq)]
44enum GfxObj {
45    Buffer(u64),
46    Other,
47    Destroyed,
48}
49
50static STATE: Mutex<State> = Mutex::new(State {
51    frame_rate: 60.0,
52    frames: 0,
53    clock: (0.0, 0, 60.0),
54    now_ms: 0.0,
55    assets: BTreeMap::new(),
56    params: BTreeMap::new(),
57    storage: BTreeMap::new(),
58    storage_used: 0,
59    saves: 0,
60    pads: [0; 4],
61    text: String::new(),
62    input_mode: 0,
63    channels: 2,
64    hashing: true,
65    video_hash: FNV_INIT,
66    audio_hash: FNV_INIT,
67    presented: 0,
68    size: (0, 0),
69    audio_frames: 0,
70    gfx: Vec::new(),
71});
72
73const FNV_INIT: u32 = 0x811c_9dc5;
74const STORAGE_MAX_VALUE: usize = 1 << 20;
75const STORAGE_QUOTA: usize = 16 << 20;
76
77fn fnv(mut h: u32, bytes: &[u8]) -> u32 {
78    for &b in bytes {
79        h = (h ^ b as u32).wrapping_mul(0x0100_0193);
80    }
81    h
82}
83
84fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
85    f(&mut STATE.lock().unwrap_or_else(|e| e.into_inner()))
86}
87
88fn valid_key(k: &str) -> bool {
89    !k.is_empty()
90        && k.len() <= 128
91        && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
92        && k != "."
93        && k != ".."
94}
95
96/// Harness API.
97pub fn set_asset(name: &str, bytes: Vec<u8>) {
98    with(|s| s.assets.insert(name.into(), bytes));
99}
100pub fn set_param(name: &str, value: &str) {
101    with(|s| s.params.insert(name.into(), value.into()));
102}
103pub fn set_pad(player: usize, buttons: u32) {
104    with(|s| s.pads[player] = buttons);
105}
106/// Text returned by `text_input` until the next [`end_frame`].
107pub fn set_text(text: &str) {
108    with(|s| s.text = text.into());
109}
110pub fn set_hashing(on: bool) {
111    with(|s| s.hashing = on);
112}
113
114/// Advance the virtual clock to the start of frame `frames` (as the runners'
115/// `VirtualClock`: monotonic across frame rate changes).
116fn tick(s: &mut State) {
117    let (base_ms, base_frame, rate) = &mut s.clock;
118    if s.frame_rate != *rate {
119        *base_ms += (s.frames - *base_frame) as f64 * 1000.0 / *rate;
120        *base_frame = s.frames;
121        *rate = s.frame_rate;
122    }
123    s.now_ms = *base_ms + (s.frames - *base_frame) as f64 * 1000.0 / *rate;
124}
125
126/// Call before each gasm_frame: time_ms is the start of that frame.
127pub fn begin_frame() {
128    with(tick);
129}
130
131/// Call after each gasm_frame so time advances.
132pub fn end_frame() {
133    with(|s| {
134        s.frames += 1;
135        s.text.clear();
136        tick(s);
137    });
138}
139
140pub struct Stats {
141    pub frame_rate: f64,
142    pub presented: u64,
143    pub width: u32,
144    pub height: u32,
145    pub video_hash: u32,
146    pub audio_hash: u32,
147    pub audio_frames: u64,
148}
149
150pub fn stats() -> Stats {
151    with(|s| Stats {
152        frame_rate: s.frame_rate,
153        presented: s.presented,
154        width: s.size.0,
155        height: s.size.1,
156        video_hash: s.video_hash,
157        audio_hash: s.audio_hash,
158        audio_frames: s.audio_frames,
159    })
160}
161
162/// Same signatures as the wasm imports (see sys.rs).
163#[allow(clippy::missing_safety_doc)]
164pub mod abi {
165    use super::*;
166
167    unsafe fn bytes<'a>(ptr: *const u8, len: u32) -> &'a [u8] {
168        if len == 0 { &[] } else { unsafe { std::slice::from_raw_parts(ptr, len as usize) } }
169    }
170    /// A string argument; runners trap on invalid UTF-8.
171    unsafe fn text(ptr: *const u8, len: u32) -> String {
172        String::from_utf8(unsafe { bytes(ptr, len) }.to_vec()).expect("string argument is not UTF-8")
173    }
174    unsafe fn copy_out(src: &[u8], dst: *mut u8, cap: u32) -> i32 {
175        if src.len() <= cap as usize && !src.is_empty() {
176            unsafe { std::ptr::copy_nonoverlapping(src.as_ptr(), dst, src.len()) };
177        }
178        src.len() as i32
179    }
180
181    pub unsafe fn log(ptr: *const u8, len: u32) {
182        eprintln!("[guest] {}", String::from_utf8_lossy(unsafe { bytes(ptr, len) }));
183    }
184    pub unsafe fn has(ptr: *const u8, len: u32) -> i32 {
185        let name = unsafe { text(ptr, len) };
186        crate::sys::IMPORTS.contains(&name.as_str()) as i32   // this stub implements all of them
187    }
188    pub unsafe fn time_ms() -> f64 {
189        with(|s| s.now_ms)
190    }
191    /// Headless semantics: UTC.
192    pub unsafe fn utc_offset_minutes() -> i32 {
193        0
194    }
195    pub unsafe fn video_set_aspect(num: u32, den: u32) {
196        let ok = (num, den) == (0, 0) || ((1..=65535).contains(&num) && (1..=65535).contains(&den) && num as u64 * 8 >= den as u64 && den as u64 * 8 >= num as u64);
197        assert!(ok, "video_set_aspect: invalid ratio {num}:{den}");
198    }
199    /// A frame of a `gasm_run` game ends: natively the game just runs on, so
200    /// this is the frame boundary (time advances as after a `gasm_frame`).
201    pub unsafe fn yield_frame() {
202        super::end_frame();
203    }
204    pub unsafe fn set_title(ptr: *const u8, len: u32) {
205        eprintln!("[gasm] title: {}", unsafe { text(ptr, len) });
206    }
207    pub unsafe fn set_frame_rate(hz: f64) {
208        if hz.is_finite() && (1.0..=1000.0).contains(&hz) {
209            with(|s| s.frame_rate = hz);
210        }
211    }
212    pub unsafe fn video_present(ptr: *const u8, w: u32, h: u32, stride: u32) {
213        assert!(w > 0 && h > 0 && w <= 4096 && h <= 4096 && stride >= w * 4, "video_present: bad geometry {w}x{h} stride {stride}");
214        with(|s| {
215            if s.hashing {
216                for y in 0..h {
217                    let row = unsafe { bytes(ptr.add((y * stride) as usize), w * 4) };
218                    s.video_hash = fnv(s.video_hash, row);
219                }
220            }
221            s.size = (w, h);
222            s.presented += 1;
223        })
224    }
225    pub unsafe fn audio_config(rate: u32, channels: u32) {
226        if (8000..=192_000).contains(&rate) && (channels == 1 || channels == 2) {
227            with(|s| s.channels = channels);
228        }
229    }
230    pub unsafe fn audio_push(ptr: *const f32, frames: u32) {
231        with(|s| {
232            if s.hashing {
233                let b = unsafe { bytes(ptr as *const u8, frames * s.channels * 4) };
234                s.audio_hash = fnv(s.audio_hash, b);
235            }
236            s.audio_frames += frames as u64;
237        })
238    }
239    pub unsafe fn input_pad(player: u32) -> u32 {
240        with(|s| s.pads.get(player as usize).copied().unwrap_or(0))
241    }
242    // raw input: like a headless run with an empty script (keyboard and pointer
243    // present, nothing pressed, pointer at 0,0 in a 1280x720 drawable, no gamepads)
244    pub unsafe fn input_mode(flags: u32) {
245        with(|s| s.input_mode = flags & 7);
246    }
247    pub unsafe fn key_state(dst: *mut u8, len: u32) -> i32 {
248        let n = (len as usize).min(32);
249        unsafe { std::ptr::write_bytes(dst, 0, n) };
250        32
251    }
252    pub unsafe fn key_events(_: *mut u8, _: u32) -> i32 {
253        0
254    }
255    pub unsafe fn pointer(dst: *mut u8, cap: u32) -> i32 {
256        if cap >= 48 {
257            let (fw, fh, mode) = with(|s| (s.size.0 as f64, s.size.1 as f64, s.input_mode));
258            let (fx, fy) = if fw > 0.0 && fh > 0.0 {
259                let scale = (1280.0 / fw).min(720.0 / fh);
260                ((-(1280.0 - fw * scale) / 2.0 / scale) as f32, (-(720.0 - fh * scale) / 2.0 / scale) as f32)
261            } else {
262                (0.0, 0.0)
263            };
264            let mut b = [0u8; 48];
265            b[8..12].copy_from_slice(&fx.to_le_bytes());
266            b[12..16].copy_from_slice(&fy.to_le_bytes());
267            b[44..48].copy_from_slice(&(1 | (mode & 6)).to_le_bytes());
268            unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), dst, 48) };
269        }
270        48
271    }
272    pub unsafe fn gamepad(slot: u32, dst: *mut u8, cap: u32) -> i32 {
273        if slot > 3 {
274            return -1;
275        }
276        if cap >= 204 {
277            unsafe { std::ptr::write_bytes(dst, 0, 204) };
278        }
279        204
280    }
281    pub unsafe fn gamepad_name(_: u32, _: *mut u8, _: u32) -> i32 {
282        -1
283    }
284    pub unsafe fn text_input(dst: *mut u8, cap: u32) -> i32 {
285        with(|s| unsafe { copy_out(s.text.as_bytes(), dst, cap) })
286    }
287    pub unsafe fn asset_size(name: *const u8, len: u32) -> i32 {
288        let n = unsafe { text(name, len) };
289        with(|s| match s.assets.get(&n) {
290            None => -1,
291            Some(a) if a.len() > i32::MAX as usize => -2,
292            Some(a) => a.len() as i32,
293        })
294    }
295    pub unsafe fn asset_size64(name: *const u8, len: u32) -> i64 {
296        let n = unsafe { text(name, len) };
297        with(|s| s.assets.get(&n).map_or(-1, |a| a.len() as i64))
298    }
299    /// The stub's assets never change: 0 (or -1 if missing).
300    pub unsafe fn asset_version(name: *const u8, len: u32) -> i32 {
301        let n = unsafe { text(name, len) };
302        with(|s| if s.assets.contains_key(&n) { 0 } else { -1 })
303    }
304    pub unsafe fn asset_count() -> u32 {
305        with(|s| s.assets.len() as u32)
306    }
307    pub unsafe fn asset_name(index: u32, dst: *mut u8, cap: u32) -> i32 {
308        with(|s| match s.assets.keys().nth(index as usize) {
309            Some(n) => unsafe { copy_out(n.as_bytes(), dst, cap) },
310            None => -1,
311        })
312    }
313    pub unsafe fn asset_read(name: *const u8, len: u32, dst: *mut u8, cap: u32) -> i32 {
314        unsafe { asset_read_at64(name, len, 0, dst, cap) }
315    }
316    pub unsafe fn asset_read_at(name: *const u8, len: u32, offset: u32, dst: *mut u8, cap: u32) -> i32 {
317        unsafe { asset_read_at64(name, len, offset as u64, dst, cap) }
318    }
319    pub unsafe fn asset_read_at64(name: *const u8, len: u32, offset: u64, dst: *mut u8, cap: u32) -> i32 {
320        let n = unsafe { text(name, len) };
321        with(|s| match s.assets.get(&n) {
322            Some(a) => {
323                let start = offset.min(a.len() as u64) as usize;
324                let k = (a.len() - start).min(cap as usize);
325                unsafe { std::ptr::copy_nonoverlapping(a[start..].as_ptr(), dst, k) };
326                k as i32
327            }
328            None => -1,
329        })
330    }
331
332    // storage: in memory (like headless runners), same rules and error codes
333    pub unsafe fn storage_get(key: *const u8, len: u32, dst: *mut u8, cap: u32) -> i32 {
334        let k = unsafe { text(key, len) };
335        with(|s| match s.storage.get(&k) {
336            Some(v) => unsafe { copy_out(v, dst, cap) },
337            None => -1,
338        })
339    }
340    pub unsafe fn storage_set(key: *const u8, len: u32, data: *const u8, data_len: u32) -> i32 {
341        let k = unsafe { text(key, len) };
342        let v = unsafe { bytes(data, data_len) }.to_vec();
343        if !valid_key(&k) {
344            return crate::sys::GASM_STORAGE_ERR_KEY;
345        }
346        if v.len() > STORAGE_MAX_VALUE {
347            return crate::sys::GASM_STORAGE_ERR_SIZE;
348        }
349        with(|s| {
350            let old = s.storage.get(&k).map_or(0, |o| k.len() + o.len());
351            let used = s.storage_used - old + k.len() + v.len();
352            if used > STORAGE_QUOTA {
353                return crate::sys::GASM_STORAGE_ERR_QUOTA;
354            }
355            s.storage_used = used;
356            s.storage.insert(k, v);
357            0
358        })
359    }
360    // gasm:clipboard: copies are accepted and dropped, nothing is ever pasted (as headless runs)
361    pub unsafe fn clipboard_set_text(_text: *const u8, len: u32) -> i32 {
362        if len > 1 << 20 { -1 } else { 0 }
363    }
364    pub unsafe fn clipboard_get_text(_dst: *mut u8, _cap: u32) -> i32 {
365        -1
366    }
367    // gasm:files: saves are accepted and complete at once (as headless runs without --save-dir)
368    pub unsafe fn files_save(_name: *const u8, name_len: u32, _mime: *const u8, _mime_len: u32, _data: *const u8, len: u32) -> i32 {
369        if name_len == 0 || name_len > 255 || len as usize > 256 << 20 {
370            return -1;
371        }
372        with(|s| {
373            s.saves += 1;
374            s.saves as i32
375        })
376    }
377    pub unsafe fn files_state(handle: i32) -> i32 {
378        with(|s| {
379            assert!(handle > 0 && handle as u32 <= s.saves, "gasm:files: invalid handle {handle}");
380            crate::sys::GASM_FILES_SAVED
381        })
382    }
383    pub unsafe fn storage_count() -> u32 {
384        with(|s| s.storage.len() as u32)
385    }
386    pub unsafe fn storage_key(index: u32, dst: *mut u8, cap: u32) -> i32 {
387        with(|s| match s.storage.keys().nth(index as usize) {
388            Some(k) => unsafe { copy_out(k.as_bytes(), dst, cap) },
389            None => -1,
390        })
391    }
392    pub unsafe fn storage_delete(key: *const u8, len: u32) -> i32 {
393        let k = unsafe { text(key, len) };
394        with(|s| match s.storage.remove(&k) {
395            Some(v) => {
396                s.storage_used -= k.len() + v.len();
397                0
398            }
399            None => -1,
400        })
401    }
402
403    pub unsafe fn param(name: *const u8, len: u32, dst: *mut u8, cap: u32) -> i32 {
404        let n = unsafe { text(name, len) };
405        with(|s| match s.params.get(&n) {
406            Some(v) => unsafe { copy_out(v.as_bytes(), dst, cap) },
407            None => -1,
408        })
409    }
410
411    // gfx: null backend. Hashes uploads like the headless runners; checks handles
412    // and buffer ranges (the runners' full validation lives in gasm-host).
413    fn add(obj: GfxObj) -> u32 {
414        with(|s| {
415            s.gfx.push(obj);
416            s.gfx.len() as u32
417        })
418    }
419    fn live(s: &State, h: u32) -> GfxObj {
420        match s.gfx.get((h as usize).wrapping_sub(1)) {
421            Some(GfxObj::Destroyed) => panic!("gfx: handle {h} was destroyed"),
422            Some(o) => *o,
423            None => panic!("gfx: invalid handle {h}"),
424        }
425    }
426    fn buffer_size(s: &State, h: u32) -> u64 {
427        match live(s, h) {
428            GfxObj::Buffer(n) => n,
429            _ => panic!("gfx: handle {h} is not a buffer"),
430        }
431    }
432    pub unsafe fn gfx_width() -> u32 { 1280 }
433    pub unsafe fn gfx_height() -> u32 { 720 }
434    pub unsafe fn gfx_create_shader(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
435    pub unsafe fn gfx_create_buffer(size: u32, _: u32) -> u32 {
436        assert!(size > 0 && size % 4 == 0, "gfx.create_buffer: size {size} must be a non-zero multiple of 4");
437        add(GfxObj::Buffer(size as u64))
438    }
439    pub unsafe fn gfx_create_pipeline(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
440    pub unsafe fn gfx_create_bind_group(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
441    pub unsafe fn gfx_create_bind_group_layout(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
442    pub unsafe fn gfx_create_texture(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
443    pub unsafe fn gfx_create_sampler(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
444    #[allow(clippy::too_many_arguments)]
445    pub unsafe fn gfx_write_texture(t: u32, mip: u32, x: u32, y: u32, w: u32, h: u32, ptr: *const u8, len: u32) {
446        with(|s| {
447            live(s, t);
448            if s.hashing {
449                for v in [t, mip, x, y, w, h] {
450                    s.video_hash = fnv(s.video_hash, &v.to_le_bytes());
451                }
452                s.video_hash = fnv(s.video_hash, unsafe { bytes(ptr, len) });
453            }
454        })
455    }
456    pub unsafe fn gfx_set_bind_group_offsets(_: u32, bg: u32, _: *const u32, _: u32) {
457        with(|s| live(s, bg));
458    }
459    pub unsafe fn gfx_set_viewport(_: f32, _: f32, _: f32, _: f32, _: f32, _: f32) {}
460    pub unsafe fn gfx_set_scissor_rect(_: u32, _: u32, _: u32, _: u32) {}
461    pub unsafe fn gfx_write_buffer(buf: u32, offset: u32, ptr: *const u8, len: u32) {
462        assert!(offset % 4 == 0 && len % 4 == 0, "gfx.write_buffer: offset {offset} and length {len} must be multiples of 4");
463        with(|s| {
464            let size = buffer_size(s, buf);
465            assert!(offset as u64 + len as u64 <= size, "gfx.write_buffer: {offset}+{len} exceeds buffer size {size}");
466            if s.hashing {
467                s.video_hash = fnv(s.video_hash, unsafe { bytes(ptr, len) });
468            }
469        })
470    }
471    pub unsafe fn gfx_begin_frame(_: f32, _: f32, _: f32, _: f32) -> u32 { 0 }
472    pub unsafe fn gfx_set_pipeline(p: u32) {
473        with(|s| live(s, p));
474    }
475    pub unsafe fn gfx_set_bind_group(_: u32, bg: u32) {
476        with(|s| live(s, bg));
477    }
478    pub unsafe fn gfx_set_vertex_buffer(_: u32, buf: u32, offset: u32) {
479        with(|s| assert!(offset as u64 <= buffer_size(s, buf), "gfx.set_vertex_buffer: offset {offset} outside the buffer"));
480    }
481    pub unsafe fn gfx_set_index_buffer(buf: u32, format: u32, offset: u32) {
482        assert!(format <= 1, "gfx.set_index_buffer: format {format}");
483        with(|s| assert!(offset as u64 <= buffer_size(s, buf), "gfx.set_index_buffer: offset {offset} outside the buffer"));
484    }
485    pub unsafe fn gfx_draw(_: u32, _: u32, _: u32, _: u32) {}
486    pub unsafe fn gfx_draw_indexed(_: u32, _: u32, _: u32, _: i32, _: u32) {}
487    pub unsafe fn gfx_end_frame() {
488        with(|s| s.presented += 1);
489    }
490    pub unsafe fn gfx_destroy(h: u32) {
491        with(|s| {
492            live(s, h);
493            s.gfx[h as usize - 1] = GfxObj::Destroyed;
494        })
495    }
496
497    // net: always denied natively (no handle is ever valid)
498    pub unsafe fn net_open(_: *const u8, _: u32) -> i32 { -1 }
499    pub unsafe fn net_state(h: i32) -> u32 { panic!("gasm:net: invalid connection handle {h}") }
500    pub unsafe fn net_send(h: i32, _: *const u8, _: u32) -> i32 { panic!("gasm:net: invalid connection handle {h}") }
501    pub unsafe fn net_recv(h: i32, _: *mut u8, _: u32) -> i32 { panic!("gasm:net: invalid connection handle {h}") }
502    pub unsafe fn net_close(h: i32) { panic!("gasm:net: invalid connection handle {h}") }
503    // no network here (headless semantics): every request is refused
504    pub unsafe fn fetch_request(_: *const u8, _: u32, _: *const u8, _: u32) -> i32 { -1 }
505    pub unsafe fn fetch_state(h: i32) -> u32 { panic!("gasm:fetch: invalid handle {h}") }
506    pub unsafe fn fetch_status(h: i32) -> i32 { panic!("gasm:fetch: invalid handle {h}") }
507    pub unsafe fn fetch_headers(h: i32, _: *mut u8, _: u32) -> i32 { panic!("gasm:fetch: invalid handle {h}") }
508    pub unsafe fn fetch_read(h: i32, _: *mut u8, _: u32) -> i32 { panic!("gasm:fetch: invalid handle {h}") }
509    pub unsafe fn fetch_close(h: i32) { panic!("gasm:fetch: invalid handle {h}") }
510
511    #[allow(clippy::too_many_arguments)]
512    mod gl {
513        include!("native_gl.rs");
514    }
515    pub use gl::*;
516
517    pub unsafe fn proc_exit(code: i32) -> ! {
518        std::process::exit(code)
519    }
520}