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 max_threads() -> u32 {
193        0
194    }
195    pub unsafe fn utc_offset_minutes() -> i32 {
196        0
197    }
198    pub unsafe fn video_set_aspect(num: u32, den: u32) {
199        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);
200        assert!(ok, "video_set_aspect: invalid ratio {num}:{den}");
201    }
202    /// A frame of a `gasm_run` game ends: natively the game just runs on, so
203    /// this is the frame boundary (time advances as after a `gasm_frame`).
204    pub unsafe fn yield_frame() {
205        super::end_frame();
206    }
207    pub unsafe fn set_title(ptr: *const u8, len: u32) {
208        eprintln!("[gasm] title: {}", unsafe { text(ptr, len) });
209    }
210    pub unsafe fn set_frame_rate(hz: f64) {
211        if hz.is_finite() && (1.0..=1000.0).contains(&hz) {
212            with(|s| s.frame_rate = hz);
213        }
214    }
215    pub unsafe fn video_present(ptr: *const u8, w: u32, h: u32, stride: u32) {
216        assert!(w > 0 && h > 0 && w <= 4096 && h <= 4096 && stride >= w * 4, "video_present: bad geometry {w}x{h} stride {stride}");
217        with(|s| {
218            if s.hashing {
219                for y in 0..h {
220                    let row = unsafe { bytes(ptr.add((y * stride) as usize), w * 4) };
221                    s.video_hash = fnv(s.video_hash, row);
222                }
223            }
224            s.size = (w, h);
225            s.presented += 1;
226        })
227    }
228    pub unsafe fn audio_config(rate: u32, channels: u32) {
229        if (8000..=192_000).contains(&rate) && (channels == 1 || channels == 2) {
230            with(|s| s.channels = channels);
231        }
232    }
233    pub unsafe fn audio_push(ptr: *const f32, frames: u32) {
234        with(|s| {
235            if s.hashing {
236                let b = unsafe { bytes(ptr as *const u8, frames * s.channels * 4) };
237                s.audio_hash = fnv(s.audio_hash, b);
238            }
239            s.audio_frames += frames as u64;
240        })
241    }
242    pub unsafe fn input_pad(player: u32) -> u32 {
243        with(|s| s.pads.get(player as usize).copied().unwrap_or(0))
244    }
245    // raw input: like a headless run with an empty script (keyboard and pointer
246    // present, nothing pressed, pointer at 0,0 in a 1280x720 drawable, no gamepads)
247    pub unsafe fn input_mode(flags: u32) {
248        with(|s| s.input_mode = flags & 7);
249    }
250    pub unsafe fn key_state(dst: *mut u8, len: u32) -> i32 {
251        let n = (len as usize).min(32);
252        unsafe { std::ptr::write_bytes(dst, 0, n) };
253        32
254    }
255    pub unsafe fn key_events(_: *mut u8, _: u32) -> i32 {
256        0
257    }
258    pub unsafe fn pointer(dst: *mut u8, cap: u32) -> i32 {
259        if cap >= 48 {
260            let (fw, fh, mode) = with(|s| (s.size.0 as f64, s.size.1 as f64, s.input_mode));
261            let (fx, fy) = if fw > 0.0 && fh > 0.0 {
262                let scale = (1280.0 / fw).min(720.0 / fh);
263                ((-(1280.0 - fw * scale) / 2.0 / scale) as f32, (-(720.0 - fh * scale) / 2.0 / scale) as f32)
264            } else {
265                (0.0, 0.0)
266            };
267            let mut b = [0u8; 48];
268            b[8..12].copy_from_slice(&fx.to_le_bytes());
269            b[12..16].copy_from_slice(&fy.to_le_bytes());
270            b[44..48].copy_from_slice(&(1 | (mode & 6)).to_le_bytes());
271            unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), dst, 48) };
272        }
273        48
274    }
275    pub unsafe fn gamepad(slot: u32, dst: *mut u8, cap: u32) -> i32 {
276        if slot > 3 {
277            return -1;
278        }
279        if cap >= 204 {
280            unsafe { std::ptr::write_bytes(dst, 0, 204) };
281        }
282        204
283    }
284    pub unsafe fn gamepad_name(_: u32, _: *mut u8, _: u32) -> i32 {
285        -1
286    }
287    pub unsafe fn text_input(dst: *mut u8, cap: u32) -> i32 {
288        with(|s| unsafe { copy_out(s.text.as_bytes(), dst, cap) })
289    }
290    pub unsafe fn asset_size(name: *const u8, len: u32) -> i32 {
291        let n = unsafe { text(name, len) };
292        with(|s| match s.assets.get(&n) {
293            None => -1,
294            Some(a) if a.len() > i32::MAX as usize => -2,
295            Some(a) => a.len() as i32,
296        })
297    }
298    pub unsafe fn asset_size64(name: *const u8, len: u32) -> i64 {
299        let n = unsafe { text(name, len) };
300        with(|s| s.assets.get(&n).map_or(-1, |a| a.len() as i64))
301    }
302    /// The stub's assets never change: 0 (or -1 if missing).
303    pub unsafe fn asset_version(name: *const u8, len: u32) -> i32 {
304        let n = unsafe { text(name, len) };
305        with(|s| if s.assets.contains_key(&n) { 0 } else { -1 })
306    }
307    pub unsafe fn asset_count() -> u32 {
308        with(|s| s.assets.len() as u32)
309    }
310    pub unsafe fn asset_name(index: u32, dst: *mut u8, cap: u32) -> i32 {
311        with(|s| match s.assets.keys().nth(index as usize) {
312            Some(n) => unsafe { copy_out(n.as_bytes(), dst, cap) },
313            None => -1,
314        })
315    }
316    pub unsafe fn asset_read(name: *const u8, len: u32, dst: *mut u8, cap: u32) -> i32 {
317        unsafe { asset_read_at64(name, len, 0, dst, cap) }
318    }
319    pub unsafe fn asset_read_at(name: *const u8, len: u32, offset: u32, dst: *mut u8, cap: u32) -> i32 {
320        unsafe { asset_read_at64(name, len, offset as u64, dst, cap) }
321    }
322    pub unsafe fn asset_read_at64(name: *const u8, len: u32, offset: u64, dst: *mut u8, cap: u32) -> i32 {
323        let n = unsafe { text(name, len) };
324        with(|s| match s.assets.get(&n) {
325            Some(a) => {
326                let start = offset.min(a.len() as u64) as usize;
327                let k = (a.len() - start).min(cap as usize);
328                unsafe { std::ptr::copy_nonoverlapping(a[start..].as_ptr(), dst, k) };
329                k as i32
330            }
331            None => -1,
332        })
333    }
334
335    // storage: in memory (like headless runners), same rules and error codes
336    pub unsafe fn storage_get(key: *const u8, len: u32, dst: *mut u8, cap: u32) -> i32 {
337        let k = unsafe { text(key, len) };
338        with(|s| match s.storage.get(&k) {
339            Some(v) => unsafe { copy_out(v, dst, cap) },
340            None => -1,
341        })
342    }
343    pub unsafe fn storage_set(key: *const u8, len: u32, data: *const u8, data_len: u32) -> i32 {
344        let k = unsafe { text(key, len) };
345        let v = unsafe { bytes(data, data_len) }.to_vec();
346        if !valid_key(&k) {
347            return crate::sys::GASM_STORAGE_ERR_KEY;
348        }
349        if v.len() > STORAGE_MAX_VALUE {
350            return crate::sys::GASM_STORAGE_ERR_SIZE;
351        }
352        with(|s| {
353            let old = s.storage.get(&k).map_or(0, |o| k.len() + o.len());
354            let used = s.storage_used - old + k.len() + v.len();
355            if used > STORAGE_QUOTA {
356                return crate::sys::GASM_STORAGE_ERR_QUOTA;
357            }
358            s.storage_used = used;
359            s.storage.insert(k, v);
360            0
361        })
362    }
363    // gasm:clipboard: copies are accepted and dropped, nothing is ever pasted (as headless runs)
364    pub unsafe fn clipboard_set_text(_text: *const u8, len: u32) -> i32 {
365        if len > 1 << 20 { -1 } else { 0 }
366    }
367    pub unsafe fn clipboard_get_text(_dst: *mut u8, _cap: u32) -> i32 {
368        -1
369    }
370    // gasm:files: saves are accepted and complete at once (as headless runs without --save-dir)
371    pub unsafe fn files_save(_name: *const u8, name_len: u32, _mime: *const u8, _mime_len: u32, _data: *const u8, len: u32) -> i32 {
372        if name_len == 0 || name_len > 255 || len as usize > 256 << 20 {
373            return -1;
374        }
375        with(|s| {
376            s.saves += 1;
377            s.saves as i32
378        })
379    }
380    pub unsafe fn files_state(handle: i32) -> i32 {
381        with(|s| {
382            assert!(handle > 0 && handle as u32 <= s.saves, "gasm:files: invalid handle {handle}");
383            crate::sys::GASM_FILES_SAVED
384        })
385    }
386    pub unsafe fn storage_count() -> u32 {
387        with(|s| s.storage.len() as u32)
388    }
389    pub unsafe fn storage_key(index: u32, dst: *mut u8, cap: u32) -> i32 {
390        with(|s| match s.storage.keys().nth(index as usize) {
391            Some(k) => unsafe { copy_out(k.as_bytes(), dst, cap) },
392            None => -1,
393        })
394    }
395    pub unsafe fn storage_delete(key: *const u8, len: u32) -> i32 {
396        let k = unsafe { text(key, len) };
397        with(|s| match s.storage.remove(&k) {
398            Some(v) => {
399                s.storage_used -= k.len() + v.len();
400                0
401            }
402            None => -1,
403        })
404    }
405
406    pub unsafe fn param(name: *const u8, len: u32, dst: *mut u8, cap: u32) -> i32 {
407        let n = unsafe { text(name, len) };
408        with(|s| match s.params.get(&n) {
409            Some(v) => unsafe { copy_out(v.as_bytes(), dst, cap) },
410            None => -1,
411        })
412    }
413
414    // gfx: null backend. Hashes uploads like the headless runners; checks handles
415    // and buffer ranges (the runners' full validation lives in gasm-host).
416    fn add(obj: GfxObj) -> u32 {
417        with(|s| {
418            s.gfx.push(obj);
419            s.gfx.len() as u32
420        })
421    }
422    fn live(s: &State, h: u32) -> GfxObj {
423        match s.gfx.get((h as usize).wrapping_sub(1)) {
424            Some(GfxObj::Destroyed) => panic!("gfx: handle {h} was destroyed"),
425            Some(o) => *o,
426            None => panic!("gfx: invalid handle {h}"),
427        }
428    }
429    fn buffer_size(s: &State, h: u32) -> u64 {
430        match live(s, h) {
431            GfxObj::Buffer(n) => n,
432            _ => panic!("gfx: handle {h} is not a buffer"),
433        }
434    }
435    pub unsafe fn gfx_width() -> u32 { 1280 }
436    pub unsafe fn gfx_height() -> u32 { 720 }
437    pub unsafe fn gfx_create_shader(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
438    pub unsafe fn gfx_create_buffer(size: u32, _: u32) -> u32 {
439        assert!(size > 0 && size % 4 == 0, "gfx.create_buffer: size {size} must be a non-zero multiple of 4");
440        add(GfxObj::Buffer(size as u64))
441    }
442    pub unsafe fn gfx_create_pipeline(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
443    pub unsafe fn gfx_create_bind_group(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
444    pub unsafe fn gfx_create_bind_group_layout(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
445    pub unsafe fn gfx_create_texture(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
446    pub unsafe fn gfx_create_sampler(_: *const u8, _: u32) -> u32 { add(GfxObj::Other) }
447    #[allow(clippy::too_many_arguments)]
448    pub unsafe fn gfx_write_texture(t: u32, mip: u32, x: u32, y: u32, w: u32, h: u32, ptr: *const u8, len: u32) {
449        with(|s| {
450            live(s, t);
451            if s.hashing {
452                for v in [t, mip, x, y, w, h] {
453                    s.video_hash = fnv(s.video_hash, &v.to_le_bytes());
454                }
455                s.video_hash = fnv(s.video_hash, unsafe { bytes(ptr, len) });
456            }
457        })
458    }
459    pub unsafe fn gfx_set_bind_group_offsets(_: u32, bg: u32, _: *const u32, _: u32) {
460        with(|s| live(s, bg));
461    }
462    pub unsafe fn gfx_set_viewport(_: f32, _: f32, _: f32, _: f32, _: f32, _: f32) {}
463    pub unsafe fn gfx_set_scissor_rect(_: u32, _: u32, _: u32, _: u32) {}
464    pub unsafe fn gfx_write_buffer(buf: u32, offset: u32, ptr: *const u8, len: u32) {
465        assert!(offset % 4 == 0 && len % 4 == 0, "gfx.write_buffer: offset {offset} and length {len} must be multiples of 4");
466        with(|s| {
467            let size = buffer_size(s, buf);
468            assert!(offset as u64 + len as u64 <= size, "gfx.write_buffer: {offset}+{len} exceeds buffer size {size}");
469            if s.hashing {
470                s.video_hash = fnv(s.video_hash, unsafe { bytes(ptr, len) });
471            }
472        })
473    }
474    pub unsafe fn gfx_begin_frame(_: f32, _: f32, _: f32, _: f32) -> u32 { 0 }
475    pub unsafe fn gfx_set_pipeline(p: u32) {
476        with(|s| live(s, p));
477    }
478    pub unsafe fn gfx_set_bind_group(_: u32, bg: u32) {
479        with(|s| live(s, bg));
480    }
481    pub unsafe fn gfx_set_vertex_buffer(_: u32, buf: u32, offset: u32) {
482        with(|s| assert!(offset as u64 <= buffer_size(s, buf), "gfx.set_vertex_buffer: offset {offset} outside the buffer"));
483    }
484    pub unsafe fn gfx_set_index_buffer(buf: u32, format: u32, offset: u32) {
485        assert!(format <= 1, "gfx.set_index_buffer: format {format}");
486        with(|s| assert!(offset as u64 <= buffer_size(s, buf), "gfx.set_index_buffer: offset {offset} outside the buffer"));
487    }
488    pub unsafe fn gfx_draw(_: u32, _: u32, _: u32, _: u32) {}
489    pub unsafe fn gfx_draw_indexed(_: u32, _: u32, _: u32, _: i32, _: u32) {}
490    pub unsafe fn gfx_end_frame() {
491        with(|s| s.presented += 1);
492    }
493    pub unsafe fn gfx_destroy(h: u32) {
494        with(|s| {
495            live(s, h);
496            s.gfx[h as usize - 1] = GfxObj::Destroyed;
497        })
498    }
499
500    // net: always denied natively (no handle is ever valid)
501    pub unsafe fn net_open(_: *const u8, _: u32) -> i32 { -1 }
502    pub unsafe fn net_state(h: i32) -> u32 { panic!("gasm:net: invalid connection handle {h}") }
503    pub unsafe fn net_send(h: i32, _: *const u8, _: u32) -> i32 { panic!("gasm:net: invalid connection handle {h}") }
504    pub unsafe fn net_recv(h: i32, _: *mut u8, _: u32) -> i32 { panic!("gasm:net: invalid connection handle {h}") }
505    pub unsafe fn net_close(h: i32) { panic!("gasm:net: invalid connection handle {h}") }
506    // no network here (headless semantics): every request is refused
507    pub unsafe fn fetch_request(_: *const u8, _: u32, _: *const u8, _: u32) -> i32 { -1 }
508    pub unsafe fn fetch_state(h: i32) -> u32 { panic!("gasm:fetch: invalid handle {h}") }
509    pub unsafe fn fetch_status(h: i32) -> i32 { panic!("gasm:fetch: invalid handle {h}") }
510    pub unsafe fn fetch_headers(h: i32, _: *mut u8, _: u32) -> i32 { panic!("gasm:fetch: invalid handle {h}") }
511    pub unsafe fn fetch_read(h: i32, _: *mut u8, _: u32) -> i32 { panic!("gasm:fetch: invalid handle {h}") }
512    pub unsafe fn fetch_close(h: i32) { panic!("gasm:fetch: invalid handle {h}") }
513
514    #[allow(clippy::too_many_arguments)]
515    mod gl {
516        include!("native_gl.rs");
517    }
518    pub use gl::*;
519
520    pub unsafe fn proc_exit(code: i32) -> ! {
521        std::process::exit(code)
522    }
523}