sm64_binds/sm64/memory.rs
1//! A game's linear memory: its layout, reading it, and copying it between
2//! games and save states.
3
4use std::ops::Range;
5
6use anyhow::{Error, Result};
7
8use super::SM64Game;
9use super::wasm_module::DataSegments;
10
11/// Where a game's linear memory is constant, read from its WASM.
12///
13/// Linear memory is not one mutable region but two, with the read-only data
14/// between them. For the build this crate ships:
15///
16/// ```text
17/// 0x000000 ┌────────────────────────┐
18/// │ stack (mutable) │ <- emscripten stack, rewritten every frame
19/// 0x010000 ├────────────────────────┤
20/// │ .rodata (constant) │ <- excluded from save states and copies
21/// 0x7b4620 ├────────────────────────┤
22/// │ .data, .bss and heap │ <- mutable, most of the save state
23/// └────────────────────────┘
24/// ```
25///
26/// wasm-ld writes `.rodata` as the first data segment and `.data` as the
27/// next, so the read-only range is the first segment's. With fewer than two
28/// segments it cannot tell them apart and treats all of memory as mutable.
29/// `tests/save_state_ranges.rs` and `tests/lockstep.rs` check the range never
30/// changes while playing.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub(super) struct MemoryLayout {
33 read_only_start: usize,
34 read_only_end: usize,
35}
36
37impl MemoryLayout {
38 pub(super) fn from_data(data: &DataSegments) -> MemoryLayout {
39 match data.as_slice() {
40 [(address, bytes), _, ..] => MemoryLayout {
41 read_only_start: *address,
42 read_only_end: address + bytes.len(),
43 },
44 _ => MemoryLayout {
45 read_only_start: 0,
46 read_only_end: 0,
47 },
48 }
49 }
50
51 /// The bytes before the read-only data: the stack.
52 pub(super) fn stack_len(&self) -> usize {
53 self.read_only_start
54 }
55
56 /// The mutable regions, as half-open `[start, end)` offsets. The second
57 /// ends at `usize::MAX`, to be clamped to the size of linear memory.
58 pub(super) fn mutable_ranges(&self) -> [(usize, usize); 2] {
59 [(0, self.read_only_start), (self.read_only_end, usize::MAX)]
60 }
61}
62
63impl SM64Game {
64 /// The part of linear memory that holds the game's constant data
65 /// (`.rodata`), which never changes while playing. Save states and copies
66 /// leave it out: they are the bytes before it (the stack) and from its
67 /// end onwards. Read from the WASM, so it follows rebuilds.
68 pub fn read_only_memory(&self) -> Range<usize> {
69 self.layout.read_only_start..self.layout.read_only_end
70 }
71
72 /// Linear memory's address and size, valid until it grows or the game is
73 /// next used mutably.
74 pub(super) fn mem(&self) -> (*mut u8, usize) {
75 let view = self.exports.memory.view(&self.store);
76 (view.data_ptr(), view.data_size() as usize)
77 }
78
79 /// Like [`SM64Game::mem`], for writing through: counts as a change to the
80 /// game's memory.
81 pub(super) fn mem_mut(&mut self) -> (*mut u8, usize) {
82 self.sync.touch();
83 self.mem()
84 }
85
86 /// Calls `f` with all of linear memory, without copying it.
87 pub fn with_memory<R>(&self, f: impl FnOnce(&[u8]) -> R) -> R {
88 let (ptr, len) = self.mem();
89 // SAFETY: valid for `len` bytes while `self` is borrowed, which
90 // outlasts the call; nothing can change it meanwhile.
91 f(unsafe { std::slice::from_raw_parts(ptr, len) })
92 }
93
94 /// Copies `buf.len()` bytes of linear memory starting at `addr` into `buf`.
95 pub fn read_memory(&self, addr: u32, buf: &mut [u8]) -> Result<()> {
96 self.with_memory(|memory| {
97 let source = (addr as usize)
98 .checked_add(buf.len())
99 .and_then(|end| memory.get(addr as usize..end))
100 .ok_or_else(|| {
101 Error::msg(format!(
102 "read of {} bytes at {addr:#x} out of bounds",
103 buf.len()
104 ))
105 })?;
106 buf.copy_from_slice(source);
107 Ok(())
108 })
109 }
110
111 /// Grows linear memory so `heap_len` bytes fit after the read-only data.
112 fn expand_memory(&mut self, heap_len: usize) -> Result<(), Error> {
113 self.expand_memory_to((self.layout.read_only_end + heap_len) as u64)
114 }
115
116 fn expand_memory_to(&mut self, total_bytes: u64) -> Result<(), Error> {
117 if self.mem().1 as u64 >= total_bytes {
118 return Ok(());
119 }
120 let (store, exports) = self.parts_mut();
121 exports.memory.grow_at_least(store, total_bytes)?;
122
123 // grow_at_least rounds up to a page, but a runtime may refuse growth
124 // entirely; re-check so no caller writes out of bounds.
125 let actual = self.mem().1 as u64;
126 if actual < total_bytes {
127 return Err(Error::msg(format!(
128 "could not grow linear memory to {total_bytes} bytes (got {actual})"
129 )));
130 }
131 Ok(())
132 }
133
134 /// The mutable regions of `memory` (this game's): the stack before the
135 /// read-only data, and everything after it.
136 pub(super) fn mutable_parts<'m>(&self, memory: &'m [u8]) -> (&'m [u8], &'m [u8]) {
137 let len = memory.len();
138 (
139 &memory[..self.layout.read_only_start.min(len)],
140 &memory[self.layout.read_only_end.min(len)..],
141 )
142 }
143
144 /// Writes mutable regions as [`SM64Game::mutable_parts`] lays them out:
145 /// the stack, then the heap. A short slice leaves the rest untouched.
146 pub(super) fn write_mutable_bytes(&mut self, bytes: &[u8]) -> Result<(), Error> {
147 // Size the destination for the largest state it might hold, then place
148 // the ranges. A short slice leaves the trailing range untouched.
149 let stack_len = self.layout.stack_len();
150 let stack = bytes.len().min(stack_len);
151 let heap = bytes.len().saturating_sub(stack_len);
152 self.expand_memory(heap)?;
153
154 let (ptr, _) = self.mem_mut();
155
156 // SAFETY: `expand_memory` verified linear memory reaches
157 // `read_only_end + heap`, which is past `stack <= read_only_start`.
158 // `bytes` is a separate allocation, so neither copy can overlap.
159 unsafe {
160 std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, stack);
161 if heap > 0 {
162 std::ptr::copy_nonoverlapping(
163 bytes.as_ptr().add(stack_len),
164 ptr.add(self.layout.read_only_end),
165 heap,
166 );
167 }
168 }
169 Ok(())
170 }
171
172 /// Makes this game a copy of `source`: copies its mutable regions, without
173 /// materialising a save state in between.
174 ///
175 /// If you repeatedly load from a previous state (like a tree search), [`SM64Game::sync_from`]
176 /// is faster: it copies back only the pages that have changed.
177 ///
178 /// Fails if `source` is a different build of the game.
179 pub fn copy_from(&mut self, source: &SM64Game) -> Result<(), Error> {
180 if source.build_id != self.build_id || source.layout != self.layout {
181 return Err(Error::msg(
182 "copy_from: the source game is a different build of the game",
183 ));
184 }
185 let (src_ptr, src_size) = source.mem();
186
187 // This game has to be at least as large as the source's mutable
188 // ranges. The stack needs no growth, only the heap does. Growing can
189 // move this game's base pointer, so its view is taken after.
190 let needed = src_size.saturating_sub(self.layout.read_only_end);
191 self.expand_memory(needed)?;
192
193 let (dst_ptr, dst_size) = self.mem_mut();
194
195 for (start, end) in self.layout.mutable_ranges() {
196 let src_end = end.min(src_size);
197 let dst_end = end.min(dst_size);
198 let len = src_end.min(dst_end).saturating_sub(start);
199 if len == 0 {
200 continue;
201 }
202 // SAFETY: `len` bytes are readable from `start` in the source and
203 // `expand_memory` guaranteed the same range is writable here. The
204 // two memories are distinct allocations, so the ranges cannot
205 // overlap.
206 unsafe {
207 std::ptr::copy_nonoverlapping(src_ptr.add(start), dst_ptr.add(start), len);
208 }
209 }
210 Ok(())
211 }
212}