Repository navigation
Expand file tree
/
Copy pathruntime.rs
More file actions
320 lines (284 loc) · 11.8 KB
/
Copy pathruntime.rs
File metadata and controls
320 lines (284 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use std::collections::BTreeMap;
use std::fs::{File, OpenOptions, create_dir_all};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
const IMPORT_MODULE: &str = "env";
pub const SCREEN_WIDTH: usize = 320;
pub const SCREEN_HEIGHT: usize = 200;
pub struct Runtime {
store: Store,
update: tinywasm::FunctionTyped<(), ()>,
framebuffer: tinywasm::FunctionTyped<(), i32>,
key_down: tinywasm::FunctionTyped<i32, ()>,
key_up: tinywasm::FunctionTyped<i32, ()>,
memory: tinywasm::Memory,
}
impl Runtime {
pub fn new(wad_path: PathBuf, guest_path: PathBuf) -> Result<Self> {
let module = tinywasm::parse_file(&guest_path)?;
let mut store = Store::default().with_state(HostState::new(wad_path));
let imports = build_imports();
let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let wad_path_buf = instance.func::<(), i32>(&store, "tinywasm_doom_wad_path_buf")?;
let init = instance.func::<(), ()>(&store, "tinywasm_doom_init")?;
let update = instance.func::<(), ()>(&store, "tinywasm_doom_update")?;
let framebuffer = instance.func::<(), i32>(&store, "tinywasm_doom_framebuffer")?;
let key_down = instance.func::<i32, ()>(&store, "tinywasm_doom_key_down")?;
let key_up = instance.func::<i32, ()>(&store, "tinywasm_doom_key_up")?;
let memory = instance.memory("memory")?;
let buf_ptr = wad_path_buf.call(&mut store, ())? as usize;
let wad_path_string = store.state::<HostState>().unwrap().wad_path.to_string_lossy().into_owned();
memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?;
init.call(&mut store, ())?;
Ok(Self { store, update, framebuffer, key_down, key_up, memory })
}
pub fn tick(&mut self) -> Result<()> {
self.update.call(&mut self.store, ())?;
Ok(())
}
pub fn write_framebuffer(&mut self, dst: &mut [u32]) -> Result<()> {
let ptr = self.framebuffer.call(&mut self.store, ())? as u32 as usize;
let framebuffer = self
.memory
.data(&self.store)?
.get(ptr..)
.and_then(|data| data.get(..SCREEN_WIDTH * SCREEN_HEIGHT * 4))
.context("framebuffer is outside guest memory")?;
anyhow::ensure!(dst.len() <= SCREEN_WIDTH * SCREEN_HEIGHT, "framebuffer destination is too large");
for (pixel, chunk) in dst.iter_mut().zip(framebuffer.chunks_exact(4)) {
*pixel = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32;
}
Ok(())
}
pub fn key_down(&mut self, key: i32) -> Result<()> {
self.key_down.call(&mut self.store, key)?;
Ok(())
}
pub fn key_up(&mut self, key: i32) -> Result<()> {
self.key_up.call(&mut self.store, key)?;
Ok(())
}
pub fn exited(&self) -> bool {
self.store.state::<HostState>().unwrap().exit_code.is_some()
}
}
pub struct HostState {
wad_path: PathBuf,
runtime_dir: PathBuf,
start: Instant,
files: BTreeMap<i32, File>,
next_file: i32,
exit_code: Option<i32>,
}
impl HostState {
fn new(wad_path: PathBuf) -> Self {
let runtime_dir = PathBuf::from("examples/doom/out/runtime");
let _ = create_dir_all(&runtime_dir);
Self { wad_path, runtime_dir, start: Instant::now(), files: BTreeMap::new(), next_file: 3, exit_code: None }
}
fn resolve_path(&self, path: &str) -> PathBuf {
let candidate = Path::new(path);
if candidate.is_absolute() { candidate.to_path_buf() } else { self.runtime_dir.join(candidate) }
}
fn should_redirect_to_wad(&self, requested: &str) -> bool {
let Some(file_name) = Path::new(requested).file_name().and_then(|name| name.to_str()) else {
return false;
};
let requested = file_name.to_ascii_lowercase();
let provided = self.wad_path.file_name().and_then(|name| name.to_str()).map(|name| name.to_ascii_lowercase());
match provided.as_deref() {
Some("doom1.wad") => requested == "doom1.wad",
Some("doom.wad") => requested == "doom.wad",
Some("doomu.wad") => requested == "doomu.wad",
Some("doom2.wad") => requested == "doom2.wad",
Some("doom2f.wad") => requested == "doom2f.wad",
Some("plutonia.wad") => requested == "plutonia.wad",
Some("tnt.wad") => requested == "tnt.wad",
Some(provided_name) => requested == provided_name,
None => false,
}
}
fn open_mode_options(mode: &str) -> OpenOptions {
let mut options = OpenOptions::new();
let plus = mode.as_bytes().contains(&b'+');
match mode.as_bytes().first().copied() {
Some(b'r') => {
options.read(true);
if plus {
options.write(true);
}
}
Some(b'w') => {
options.write(true).create(true).truncate(true);
if plus {
options.read(true);
}
}
Some(b'a') => {
options.write(true).create(true).append(true);
if plus {
options.read(true);
}
}
_ => {
options.read(true);
}
}
options
}
}
fn build_imports() -> Imports {
let mut imports = Imports::new();
imports.define(
IMPORT_MODULE,
"host_open",
HostFunction::from(|mut ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| {
let memory = ctx.memory("memory")?;
let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?;
let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?;
let filename = filename.to_string_lossy();
let mode = mode.to_string_lossy();
let state = ctx.state_mut::<HostState>().unwrap();
let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) {
state.wad_path.clone()
} else {
state.resolve_path(&filename)
};
if path.is_dir() {
log::debug!("guest open rejected directory: path={} mode={}", path.display(), mode);
return Ok(-1);
}
let file = match HostState::open_mode_options(&mode).open(&path) {
Ok(file) => file,
Err(err) => {
log::debug!("guest open failed: path={} mode={} err={err}", path.display(), mode);
return Ok(-1);
}
};
let handle = state.next_file;
state.next_file += 1;
state.files.insert(handle, file);
Ok(handle)
}),
);
imports.define(
IMPORT_MODULE,
"host_close",
HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| {
ctx.state_mut::<HostState>().unwrap().files.remove(&handle);
Ok(())
}),
);
imports.define(
IMPORT_MODULE,
"host_read",
HostFunction::from(|mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| {
let mut buffer = vec![0; count.max(0) as usize];
let read = {
let state = ctx.state_mut::<HostState>().unwrap();
let Some(file) = state.files.get_mut(&handle) else {
return Ok(0);
};
file.read(&mut buffer).map_err(|err| tinywasm::Error::Other(err.to_string()))?
};
ctx.memory("memory")?.copy_from_slice(ctx.store_mut(), buf_ptr as usize, &buffer[..read])?;
Ok(read as i32)
}),
);
imports.define(
IMPORT_MODULE,
"host_write",
HostFunction::from(|ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| {
let data = ctx.memory("memory")?.data(ctx.store())?;
let offset = buf_ptr as u32 as usize;
let len = count.max(0) as usize;
let data = data
.get(offset..)
.and_then(|data| data.get(..len))
.ok_or(tinywasm::Trap::MemoryOutOfBounds { offset, len, max: data.len() })?;
let state = ctx.state::<HostState>().unwrap();
let Some(mut file) = state.files.get(&handle) else {
return Ok(-1);
};
let written = file.write(data).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
Ok(written as i32)
}),
);
imports.define(
IMPORT_MODULE,
"host_seek",
HostFunction::from(|mut ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| {
let seek_from = match origin {
0 => SeekFrom::Start(offset.max(0) as u64),
1 => SeekFrom::Current(offset as i64),
2 => SeekFrom::End(offset as i64),
_ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))),
};
let state = ctx.state_mut::<HostState>().unwrap();
let Some(file) = state.files.get_mut(&handle) else {
return Ok(-1);
};
let pos = file.seek(seek_from).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
Ok(pos.min(i32::MAX as u64) as i32)
}),
);
imports.define(
IMPORT_MODULE,
"host_tell",
HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| {
let state = ctx.state_mut::<HostState>().unwrap();
let Some(file) = state.files.get_mut(&handle) else {
return Ok(-1);
};
let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?;
Ok(pos.min(i32::MAX as u64) as i32)
}),
);
imports.define(
IMPORT_MODULE,
"host_eof",
HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| {
let state = ctx.state_mut::<HostState>().unwrap();
let Some(file) = state.files.get_mut(&handle) else {
return Ok(1);
};
let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?;
let len = file.metadata().map_err(|err| tinywasm::Error::Other(err.to_string()))?.len();
Ok((pos >= len) as i32)
}),
);
imports.define(
IMPORT_MODULE,
"host_gettime",
HostFunction::from(|mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| {
let elapsed = ctx.state::<HostState>().unwrap().start.elapsed() + Duration::from_secs(1);
let sec = elapsed.as_secs().min(i32::MAX as u64) as i32;
let usec = elapsed.subsec_micros() as i32;
let memory = ctx.memory("memory")?;
memory.copy_from_slice(ctx.store_mut(), sec_ptr as usize, &sec.to_le_bytes())?;
memory.copy_from_slice(ctx.store_mut(), usec_ptr as usize, &usec.to_le_bytes())?;
Ok(())
}),
);
imports.define(
IMPORT_MODULE,
"host_exit",
HostFunction::from(|mut ctx: FuncContext<'_>, code: i32| {
ctx.state_mut::<HostState>().unwrap().exit_code = Some(code);
Ok(())
}),
);
imports.define(
IMPORT_MODULE,
"host_print",
HostFunction::from(|ctx: FuncContext<'_>, ptr: i32| {
let text = ctx.memory("memory")?.read_cstring_until_null(ctx.store(), ptr as usize, 4096)?;
log::info!("guest: {}", text.to_string_lossy());
Ok(())
}),
);
imports
}