Skip to main content

sm64_binds/sm64/
generator.rs

1//! Where games come from: the ROM turned back into the headless WASM (or a
2//! WASM given directly), and how its code is compiled ([`Backend`]: Cranelift,
3//! or the precompiled module in `pkg/`). The only way to make an [`SM64Game`].
4
5use anyhow::{Error, Result};
6use wasmer::{Engine, Module};
7
8use super::SM64Game;
9use super::memory::MemoryLayout;
10use super::util::{check_hash, unzip_bytes, xor_bytes};
11use super::wasm_module::{self, BuildId, DataSegments};
12
13/// The distributable WASM payload, XOR'd against a US `.z64` ROM.
14const XOR_BYTES: &[u8] = include_bytes!("../../pkg/sm64_headless.us.wasm.zip.xor");
15
16/// How a generator's games run the game's code.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum Backend {
19    /// The precompiled module when it was made from this WASM's code (x86-64
20    /// Linux with the `precompiled` feature), Cranelift otherwise. The
21    /// `SM64_BACKEND` environment variable (`cranelift` or `precompiled`) can
22    /// override this choice.
23    #[default]
24    Auto,
25    /// Compile the WASM with Cranelift when the generator is made.
26    Cranelift,
27    /// The precompiled module; making the generator fails if it is not for
28    /// this platform or was made from a different WASM.
29    Precompiled,
30}
31
32/// Compiles the WASM module once so that every [`SM64Game`] it creates is a
33/// cheap instantiation of shared, immutable code.
34#[derive(Debug, Clone)]
35pub struct SM64GameGenerator {
36    source: GameSource,
37}
38
39impl SM64GameGenerator {
40    /// Builds a generator from a US `.z64` ROM (8.00 MB, big endian).
41    pub fn new(rom_bytes: Vec<u8>) -> Result<Self, Error> {
42        if !check_hash(&rom_bytes) {
43            return Err(Error::msg(
44                "Invalid ROM. Should be a US copy, in z64 format (8.00MB)",
45            ));
46        };
47        Self::from_wasm(Self::rom_to_wasm_bytes(rom_bytes))
48    }
49
50    #[cfg(feature = "fs")]
51    pub fn from_file(rom_path: &str) -> Result<Self, Error> {
52        let rom_bytes = std::fs::read(rom_path)?;
53        Self::new(rom_bytes)
54    }
55
56    /// Builds a generator from a headless WASM (such as a fresh build of
57    /// `sm64-port`), bypassing ROM validation.
58    pub fn from_wasm(wasm_bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
59        Self::from_wasm_with(wasm_bytes, Backend::Auto)
60    }
61
62    /// Like [`SM64GameGenerator::from_wasm`], with a selected `backend` rather than [`Backend::Auto`].
63    pub fn from_wasm_with(wasm_bytes: impl AsRef<[u8]>, backend: Backend) -> Result<Self, Error> {
64        let wasm = wasm_bytes.as_ref();
65        let source = match backend {
66            Backend::Auto => GameSource::for_wasm(wasm)?,
67            Backend::Cranelift => GameSource::cranelift(wasm)?,
68            Backend::Precompiled => GameSource::precompiled(wasm)?.ok_or_else(|| {
69                Error::msg("the precompiled module is not for this platform or this WASM")
70            })?,
71        };
72        Ok(SM64GameGenerator { source })
73    }
74
75    pub fn create_game(&self) -> Result<SM64Game, Error> {
76        SM64Game::from_source(&self.source)
77    }
78
79    /// Recombines the distributed XOR payload with the ROM and unzips it.
80    pub fn rom_to_wasm_bytes(rom_bytes: Vec<u8>) -> Vec<u8> {
81        unzip_bytes(&xor_bytes(XOR_BYTES, &rom_bytes))
82    }
83
84    /// A new game that is a copy of `game`.
85    pub fn copy_from(&self, game: &SM64Game) -> Result<SM64Game, Error> {
86        let mut copy = self.create_game()?;
87        copy.copy_from(game)?;
88        Ok(copy)
89    }
90}
91
92/// What games are made from: the WASM compiled at load time by wasmer
93/// (Cranelift), or the precompiled module shipped in `pkg/` and the WASM's
94/// data for it.
95#[derive(Debug, Clone)]
96pub(super) struct GameSource {
97    pub(super) engine: Engine,
98    pub(super) module: Module,
99    /// For the precompiled module, which has no data: the WASM's data,
100    /// written into memory before `main_func`.
101    pub(super) segments: Option<std::sync::Arc<DataSegments>>,
102    /// The WASM's [`BuildId`], which save states are stamped with.
103    pub(super) build_id: BuildId,
104    /// Where its memory is constant, from its data.
105    pub(super) layout: MemoryLayout,
106}
107
108impl GameSource {
109    /// [`Backend::Auto`]: the precompiled module when it was made from this
110    /// WASM's code, Cranelift otherwise, unless `SM64_BACKEND` asks for
111    /// `cranelift`, or for `precompiled`, which then fails when it is not
112    /// possible.
113    fn for_wasm(wasm: &[u8]) -> Result<GameSource> {
114        let wanted = std::env::var("SM64_BACKEND").ok();
115        match wanted.as_deref() {
116            None | Some("cranelift") | Some("precompiled") => {}
117            Some(other) => {
118                return Err(Error::msg(format!(
119                    "SM64_BACKEND={other}: expected cranelift or precompiled"
120                )));
121            }
122        }
123        if wanted.as_deref() != Some("cranelift") {
124            if let Some(source) = Self::precompiled(wasm)? {
125                return Ok(source);
126            }
127            if wanted.as_deref() == Some("precompiled") {
128                return Err(Error::msg(
129                    "SM64_BACKEND=precompiled, but the precompiled module is not for this \
130                     platform or was made from a different WASM",
131                ));
132            }
133        }
134        Self::cranelift(wasm)
135    }
136
137    fn cranelift(wasm: &[u8]) -> Result<GameSource> {
138        let (code, data) = wasm_module::separate_data(wasm)?;
139        let engine = Engine::default();
140        let module = Module::new(&engine, wasm)?;
141        Ok(GameSource {
142            engine,
143            module,
144            segments: None,
145            build_id: wasm_module::build_id(&code),
146            layout: MemoryLayout::from_data(&data),
147        })
148    }
149
150    /// The precompiled module for `wasm`, if there is one for it.
151    fn precompiled(wasm: &[u8]) -> Result<Option<GameSource>> {
152        #[cfg(all(
153            feature = "precompiled",
154            target_arch = "x86_64",
155            target_os = "linux",
156            target_env = "gnu"
157        ))]
158        {
159            let (code, segments) = wasm_module::separate_data(wasm)?;
160            let build_id = wasm_module::build_id(&code);
161            Ok(
162                super::precompiled::load(&build_id)?.map(|(engine, module)| GameSource {
163                    engine,
164                    module,
165                    layout: MemoryLayout::from_data(&segments),
166                    segments: Some(std::sync::Arc::new(segments)),
167                    build_id,
168                }),
169            )
170        }
171        #[cfg(not(all(
172            feature = "precompiled",
173            target_arch = "x86_64",
174            target_os = "linux",
175            target_env = "gnu"
176        )))]
177        {
178            let _ = wasm;
179            Ok(None)
180        }
181    }
182}