1
use std::collections::HashMap;
2
use std::sync::{Arc, Mutex, RwLock};
3
use std::time::{SystemTime, UNIX_EPOCH};
4

            
5
use nomiscript::SymbolTable;
6
use wasmtime::{Caller, Engine, Linker, Memory, Module};
7

            
8
pub struct WasmHost {
9
    engine: Engine,
10
    symbol_table: Arc<RwLock<SymbolTable>>,
11
    module_cache: Arc<Mutex<HashMap<Vec<u8>, Module>>>,
12
}
13

            
14
impl WasmHost {
15
    #[must_use]
16
3346
    pub fn new(engine: Engine, symbol_table: SymbolTable) -> Self {
17
3346
        Self {
18
3346
            engine,
19
3346
            symbol_table: Arc::new(RwLock::new(symbol_table)),
20
3346
            module_cache: Arc::new(Mutex::new(HashMap::new())),
21
3346
        }
22
3346
    }
23

            
24
    #[must_use]
25
9462
    pub fn engine(&self) -> &Engine {
26
9462
        &self.engine
27
9462
    }
28

            
29
    #[must_use]
30
6764
    pub fn symbol_table(&self) -> &Arc<RwLock<SymbolTable>> {
31
6764
        &self.symbol_table
32
6764
    }
33

            
34
    #[must_use]
35
382
    pub fn module_cache(&self) -> &Arc<Mutex<HashMap<Vec<u8>, Module>>> {
36
382
        &self.module_cache
37
382
    }
38

            
39
    #[must_use]
40
3154
    pub fn execution_state(
41
3154
        &self,
42
3154
        input_offset: u32,
43
3154
        output_offset: u32,
44
3154
        strings_offset: u32,
45
3154
    ) -> ExecutionState {
46
3154
        ExecutionState {
47
3154
            input_offset,
48
3154
            output_offset,
49
3154
            strings_offset,
50
3154
            output_strings_offset: Arc::new(Mutex::new(0)),
51
3154
            memory: None,
52
3154
            symbol_table: Arc::clone(&self.symbol_table),
53
3154
        }
54
3154
    }
55
}
56

            
57
pub struct ExecutionState {
58
    pub input_offset: u32,
59
    pub output_offset: u32,
60
    pub strings_offset: u32,
61
    pub output_strings_offset: Arc<Mutex<u32>>,
62
    pub memory: Option<Memory>,
63
    pub symbol_table: Arc<RwLock<SymbolTable>>,
64
}
65

            
66
impl ExecutionState {
67
    #[must_use]
68
1
    pub fn new(input_offset: u32, output_offset: u32, strings_offset: u32) -> Self {
69
1
        Self {
70
1
            input_offset,
71
1
            output_offset,
72
1
            strings_offset,
73
1
            output_strings_offset: Arc::new(Mutex::new(0)),
74
1
            memory: None,
75
1
            symbol_table: Arc::new(RwLock::new(SymbolTable::new())),
76
1
        }
77
1
    }
78
}
79

            
80
3154
pub fn define_host_functions(linker: &mut Linker<ExecutionState>) -> wasmtime::Result<()> {
81
3154
    linker.func_wrap(
82
3154
        "env",
83
3154
        "get_input_offset",
84
209
        |caller: Caller<ExecutionState>| -> u32 { caller.data().input_offset },
85
    )?;
86

            
87
3154
    linker.func_wrap(
88
3154
        "env",
89
3154
        "get_output_offset",
90
3211
        |caller: Caller<ExecutionState>| -> u32 { caller.data().output_offset },
91
    )?;
92

            
93
3154
    linker.func_wrap(
94
3154
        "env",
95
3154
        "get_strings_offset",
96
        |caller: Caller<ExecutionState>| -> u32 { caller.data().strings_offset },
97
    )?;
98

            
99
3154
    linker.func_wrap(
100
3154
        "env",
101
3154
        "symbol_resolve",
102
        |caller: Caller<ExecutionState>, _name_ptr: u32, _name_len: u32| {
103
            let _memory = match caller.data().memory {
104
                Some(mem) => mem,
105
                None => return,
106
            };
107
            tracing::debug!(
108
                name_ptr = _name_ptr,
109
                name_len = _name_len,
110
                "symbol_resolve called"
111
            );
112
        },
113
    )?;
114

            
115
3154
    linker.func_wrap(
116
3154
        "env",
117
3154
        "write_bytes",
118
        |mut caller: Caller<ExecutionState>, dst: u32, src: u32, len: u32| -> u32 {
119
            let memory = match caller.data().memory {
120
                Some(mem) => mem,
121
                None => return 0,
122
            };
123
            let data = memory.data_mut(&mut caller);
124
            let src_start = src as usize;
125
            let src_end = src_start + len as usize;
126
            let dst_start = dst as usize;
127

            
128
            if src_end > data.len() || dst_start + len as usize > data.len() {
129
                return 0;
130
            }
131

            
132
            let bytes: Vec<u8> = data[src_start..src_end].to_vec();
133
            data[dst_start..dst_start + len as usize].copy_from_slice(&bytes);
134
            len
135
        },
136
    )?;
137

            
138
3154
    linker.func_wrap(
139
3154
        "env",
140
3154
        "write_string",
141
        |mut caller: Caller<ExecutionState>, ptr: u32, len: u32| -> u32 {
142
            let output_offset = caller.data().output_offset;
143
            let output_strings = caller.data().output_strings_offset.clone();
144

            
145
            let memory = match caller.data().memory {
146
                Some(mem) => mem,
147
                None => return 0,
148
            };
149

            
150
            let data = memory.data_mut(&mut caller);
151
            let src_start = ptr as usize;
152
            let src_end = src_start + len as usize;
153

            
154
            if src_end > data.len() {
155
                return 0;
156
            }
157

            
158
            let mut strings_offset = match output_strings.lock() {
159
                Ok(guard) => guard,
160
                Err(_) => return 0,
161
            };
162

            
163
            let current_offset = *strings_offset;
164
            let dst = output_offset as usize + current_offset as usize;
165

            
166
            if dst + len as usize > data.len() {
167
                return 0;
168
            }
169

            
170
            let bytes: Vec<u8> = data[src_start..src_end].to_vec();
171
            data[dst..dst + len as usize].copy_from_slice(&bytes);
172
            *strings_offset += len;
173

            
174
            current_offset
175
        },
176
    )?;
177

            
178
3154
    linker.func_wrap(
179
3154
        "env",
180
3154
        "log",
181
114
        |caller: Caller<ExecutionState>, level: u32, msg_ptr: u32, msg_len: u32| {
182
114
            tracing::debug!(level, msg_ptr, msg_len, "host log called");
183
114
            let memory = match caller.data().memory {
184
114
                Some(mem) => mem,
185
                None => return,
186
            };
187

            
188
114
            let data = memory.data(&caller);
189
114
            let start = msg_ptr as usize;
190
114
            let end = start + msg_len as usize;
191

            
192
114
            if end > data.len() {
193
                return;
194
114
            }
195

            
196
114
            let msg = match std::str::from_utf8(&data[start..end]) {
197
114
                Ok(s) => s,
198
                Err(_) => return,
199
            };
200

            
201
114
            match level {
202
114
                0 => tracing::debug!("[script] {msg}"),
203
                1 => tracing::info!("[script] {msg}"),
204
                2 => tracing::warn!("[script] {msg}"),
205
                _ => tracing::error!("[script] {msg}"),
206
            }
207
114
        },
208
    )?;
209

            
210
3154
    linker.func_wrap("env", "get_timestamp", || -> i64 {
211
        SystemTime::now()
212
            .duration_since(UNIX_EPOCH)
213
            .map(|d| d.as_millis() as i64)
214
            .unwrap_or(0)
215
    })?;
216

            
217
3154
    linker.func_wrap(
218
3154
        "env",
219
3154
        "generate_uuid",
220
114
        |mut caller: Caller<ExecutionState>, out_ptr: u32| {
221
114
            let memory = match caller.data().memory {
222
114
                Some(mem) => mem,
223
                None => return,
224
            };
225

            
226
114
            let uuid_bytes = uuid::Uuid::new_v4().into_bytes();
227
114
            let data = memory.data_mut(&mut caller);
228
114
            let start = out_ptr as usize;
229

            
230
114
            if start + 16 > data.len() {
231
                return;
232
114
            }
233

            
234
114
            data[start..start + 16].copy_from_slice(&uuid_bytes);
235
114
        },
236
    )?;
237

            
238
3154
    linker.func_wrap(
239
3154
        "env",
240
3154
        "get_input_entities_count",
241
        |caller: Caller<ExecutionState>| -> i32 {
242
            use crate::format::GlobalHeader;
243

            
244
            let memory = match caller.data().memory {
245
                Some(mem) => mem,
246
                None => return 0,
247
            };
248

            
249
            let input_offset = caller.data().input_offset;
250
            let data = memory.data(&caller);
251
            let input_start = input_offset as usize;
252

            
253
            if input_start + std::mem::size_of::<GlobalHeader>() > data.len() {
254
                return 0;
255
            }
256

            
257
            if let Some(header) = GlobalHeader::from_bytes(&data[input_start..]) {
258
                header.input_entity_count as i32
259
            } else {
260
                0
261
            }
262
        },
263
    )?;
264

            
265
3154
    Ok(())
266
3154
}
267

            
268
#[cfg(test)]
269
mod tests {
270
    use super::*;
271
    use crate::format::BASE_OFFSET;
272

            
273
    #[test]
274
1
    fn test_execution_state_creation() {
275
1
        let state = ExecutionState::new(BASE_OFFSET, BASE_OFFSET + 1024, BASE_OFFSET + 512);
276
1
        assert_eq!(state.input_offset, BASE_OFFSET);
277
1
        assert_eq!(state.output_offset, BASE_OFFSET + 1024);
278
1
        assert_eq!(state.strings_offset, BASE_OFFSET + 512);
279
1
    }
280

            
281
    #[test]
282
1
    fn test_wasm_host_creation() {
283
1
        let host = WasmHost::new(Engine::default(), SymbolTable::new());
284
1
        assert!(host.module_cache().lock().unwrap().is_empty());
285
1
    }
286
}