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

            
4
use nomiscript::SymbolTable;
5
use wasmtime::{AnyRef, Caller, Engine, Linker, Memory, Rooted};
6

            
7
use crate::runtime::{ModuleCache, logged_values};
8

            
9
pub struct WasmHost {
10
    engine: Engine,
11
    symbol_table: Arc<RwLock<SymbolTable>>,
12
    module_cache: ModuleCache,
13
}
14

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

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

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

            
35
    #[must_use]
36
21472
    pub fn module_cache(&self) -> &ModuleCache {
37
21472
        &self.module_cache
38
21472
    }
39

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
175
            current_offset
176
        },
177
    )?;
178

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

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

            
193
760
            if end > data.len() {
194
                return;
195
760
            }
196

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

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

            
211
2454231
    linker.func_wrap(
212
2454231
        "env",
213
2454231
        "log_value",
214
        |mut caller: Caller<ExecutionState>,
215
         args: Option<Rooted<AnyRef>>|
216
         -> wasmtime::Result<i32> {
217
            let Some(msg) = logged_values(&mut caller, args)? else {
218
                return Ok(1);
219
            };
220
            tracing::debug!("[script] {msg}");
221
            Ok(0)
222
        },
223
    )?;
224

            
225
2454231
    linker.func_wrap("env", "get_timestamp", || -> i64 {
226
        SystemTime::now()
227
            .duration_since(UNIX_EPOCH)
228
            .map_or(0, |d| d.as_millis() as i64)
229
    })?;
230

            
231
2454231
    linker.func_wrap(
232
2454231
        "env",
233
2454231
        "generate_uuid",
234
4560
        |mut caller: Caller<ExecutionState>, out_ptr: u32| {
235
4560
            let memory = match caller.data().memory {
236
4560
                Some(mem) => mem,
237
                None => return,
238
            };
239

            
240
4560
            let uuid_bytes = uuid::Uuid::new_v4().into_bytes();
241
4560
            let data = memory.data_mut(&mut caller);
242
4560
            let start = out_ptr as usize;
243

            
244
4560
            if start + 16 > data.len() {
245
                return;
246
4560
            }
247

            
248
4560
            data[start..start + 16].copy_from_slice(&uuid_bytes);
249
4560
        },
250
    )?;
251

            
252
2454231
    linker.func_wrap(
253
2454231
        "env",
254
2454231
        "get_input_entities_count",
255
3824130
        |caller: Caller<ExecutionState>| -> i32 {
256
            use crate::format::GlobalHeader;
257

            
258
3824130
            let memory = match caller.data().memory {
259
3824130
                Some(mem) => mem,
260
                None => return 0,
261
            };
262

            
263
3824130
            let input_offset = caller.data().input_offset;
264
3824130
            let data = memory.data(&caller);
265
3824130
            let input_start = input_offset as usize;
266

            
267
3824130
            if input_start + std::mem::size_of::<GlobalHeader>() > data.len() {
268
                return 0;
269
3824130
            }
270

            
271
3824130
            if let Some(header) = GlobalHeader::from_bytes(&data[input_start..]) {
272
3824130
                header.input_entity_count as i32
273
            } else {
274
                0
275
            }
276
3824130
        },
277
    )?;
278

            
279
    // Tier 3 boundary bridge: the compiler wraps each host-invoked body in
280
    // a `try_table` that catches an uncaught `$nomi_error`, reads its
281
    // code+message+detail, and calls `__nomi_raise`. Script-mode modules
282
    // (ScriptExecutor, nms) instantiate through this linker, so the bridge
283
    // must live here too — mirrors `rpc::natives::raise`.
284
2454231
    linker.func_wrap(
285
2454231
        "nomi",
286
2454231
        "__nomi_raise",
287
        |mut caller: Caller<ExecutionState>,
288
         code: Option<wasmtime::Rooted<wasmtime::ArrayRef>>,
289
         message: Option<wasmtime::Rooted<wasmtime::ArrayRef>>,
290
         detail: Option<wasmtime::Rooted<wasmtime::AnyRef>>|
291
52820
         -> wasmtime::Result<()> {
292
52820
            crate::runtime::nomi_raise(&mut caller, code, message, detail)
293
52820
        },
294
    )?;
295

            
296
2454231
    Ok(())
297
2454231
}
298

            
299
#[cfg(test)]
300
mod tests {
301
    use super::*;
302
    use crate::format::BASE_OFFSET;
303

            
304
    #[test]
305
1
    fn test_execution_state_creation() {
306
1
        let state = ExecutionState::new(BASE_OFFSET, BASE_OFFSET + 1024, BASE_OFFSET + 512);
307
1
        assert_eq!(state.input_offset, BASE_OFFSET);
308
1
        assert_eq!(state.output_offset, BASE_OFFSET + 1024);
309
1
        assert_eq!(state.strings_offset, BASE_OFFSET + 512);
310
1
    }
311

            
312
    #[test]
313
1
    fn test_wasm_host_creation() {
314
1
        let host = WasmHost::new(Engine::default(), SymbolTable::new());
315
1
        assert!(
316
1
            host.module_cache()
317
1
                .is_empty()
318
1
                .expect("cache lock must not be poisoned in fresh host")
319
        );
320
1
    }
321
}