Skip to main content

euv_core/dynamic/wasm/
fn.rs

1use super::*;
2
3/// Computes a deterministic 64-bit FNV-1a checksum over raw `.wasm` binary bytes.
4///
5/// # Arguments
6///
7/// - `&[u8]` - Raw `.wasm` binary slice.
8///
9/// # Returns
10///
11/// - `u64` - Deterministic non-zero digest.
12#[must_use]
13pub fn compute_wasm_checksum(bytes: &[u8]) -> u64 {
14    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
15    for byte in bytes.iter() {
16        hash ^= *byte as u64;
17        hash = hash.wrapping_mul(0x0100_0000_01b3);
18    }
19    hash.max(1)
20}
21
22/// Computes a deterministic keyed integrity signature tag for a `.wasm` binary and release version.
23///
24/// # Arguments
25///
26/// - `&[u8]` - Raw `.wasm` binary bytes.
27/// - `u64` - Release version number.
28/// - `&str` - Shared verification key or signing secret.
29///
30/// # Returns
31///
32/// - `String` - Formatted signature tag (`"euv-sig-v1:<hex>"`).
33#[must_use]
34pub fn compute_wasm_signature(bytes: &[u8], version: u64, signing_key: &str) -> String {
35    let mut h1: u64 = 0xcbf2_9ce4_8422_2325 ^ version.wrapping_mul(0x9E37_79B9_7F4A_7C15);
36    let mut h2: u64 = 0x8422_2325_cbf2_9ce4 ^ (bytes.len() as u64);
37    for byte in signing_key.as_bytes().iter() {
38        h1 ^= *byte as u64;
39        h1 = h1.wrapping_mul(0x0100_0000_01b3);
40        h2 = h2.rotate_left(7) ^ (*byte as u64);
41    }
42    for byte in bytes.iter() {
43        h1 ^= *byte as u64;
44        h1 = h1.wrapping_mul(0x0100_0000_01b3);
45        h2 ^= (*byte as u64).wrapping_mul(0x517c_c1b7_2722_0a95);
46        h2 = h2.rotate_left(13);
47    }
48    format!("{WASM_SIGNATURE_PREFIX}{h1:016x}{h2:016x}")
49}
50
51/// Encodes an unsigned 32-bit integer as LEB128 into `out`.
52///
53/// # Arguments
54///
55/// - `&mut Vec<u8>` - Destination byte vector.
56/// - `u32` - Unsigned integer to encode.
57pub(crate) fn write_uleb128(out: &mut Vec<u8>, mut value: u32) {
58    loop {
59        let mut byte: u8 = (value & 0x7F) as u8;
60        value >>= 7;
61        if value != 0 {
62            byte |= 0x80;
63        }
64        out.push(byte);
65        if value == 0 {
66            break;
67        }
68    }
69}
70
71/// Encodes a signed 32-bit integer as SLEB128 into `out`.
72///
73/// # Arguments
74///
75/// - `&mut Vec<u8>` - Destination byte vector.
76/// - `i32` - Signed integer to encode.
77pub(crate) fn write_sleb128(out: &mut Vec<u8>, mut value: i32) {
78    loop {
79        let byte: u8 = (value & 0x7F) as u8;
80        value >>= 7;
81        let done: bool = (value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0);
82        if done {
83            out.push(byte);
84            break;
85        }
86        out.push(byte | 0x80);
87    }
88}
89
90/// Decodes an unsigned 32-bit LEB128 integer starting at `*cursor` in `bytes`.
91///
92/// # Arguments
93///
94/// - `&[u8]` - Source WASM byte slice.
95/// - `&mut usize` - Read cursor advanced past the encoded integer.
96///
97/// # Returns
98///
99/// - `Result<u32, WasmDynamicError>` - Decoded integer or `InvalidWasmBinary`.
100pub(crate) fn read_uleb128(bytes: &[u8], cursor: &mut usize) -> Result<u32, WasmDynamicError> {
101    let mut result: u32 = 0;
102    let mut shift: u32 = 0;
103    loop {
104        let byte: u8 = *bytes.get(*cursor).ok_or_else(|| {
105            WasmDynamicError::InvalidWasmBinary("unexpected EOF in uleb128".to_string())
106        })?;
107        *cursor += 1;
108        if shift >= 35 {
109            return Err(WasmDynamicError::InvalidWasmBinary(
110                "uleb128 integer overflow".to_string(),
111            ));
112        }
113        result |= ((byte & 0x7F) as u32).wrapping_shl(shift);
114        if (byte & 0x80) == 0 {
115            return Ok(result);
116        }
117        shift += 7;
118    }
119}
120
121/// Decodes a signed 32-bit SLEB128 integer starting at `*cursor` in `bytes`.
122///
123/// # Arguments
124///
125/// - `&[u8]` - Source WASM byte slice.
126/// - `&mut usize` - Read cursor advanced past the encoded integer.
127///
128/// # Returns
129///
130/// - `Result<i32, WasmDynamicError>` - Decoded signed integer or `InvalidWasmBinary`.
131pub(crate) fn read_sleb128(bytes: &[u8], cursor: &mut usize) -> Result<i32, WasmDynamicError> {
132    let mut result: i32 = 0;
133    let mut shift: u32 = 0;
134    loop {
135        let byte: u8 = *bytes.get(*cursor).ok_or_else(|| {
136            WasmDynamicError::InvalidWasmBinary("unexpected EOF in sleb128".to_string())
137        })?;
138        *cursor += 1;
139        if shift >= 35 {
140            return Err(WasmDynamicError::InvalidWasmBinary(
141                "sleb128 integer overflow".to_string(),
142            ));
143        }
144        result |= ((byte & 0x7F) as i32).wrapping_shl(shift);
145        shift += 7;
146        if (byte & 0x80) == 0 {
147            if shift < 32 && (byte & 0x40) != 0 {
148                result |= !0_i32 << shift;
149            }
150            return Ok(result);
151        }
152    }
153}
154
155/// Reads a length-prefixed UTF-8 WebAssembly name string from `bytes`.
156///
157/// # Arguments
158///
159/// - `&[u8]` - Source WASM byte slice.
160/// - `&mut usize` - Read cursor advanced past the string.
161///
162/// # Returns
163///
164/// - `Result<String, WasmDynamicError>` - Decoded UTF-8 identifier or `InvalidWasmBinary`.
165fn read_wasm_name(bytes: &[u8], cursor: &mut usize) -> Result<String, WasmDynamicError> {
166    let len: usize = read_uleb128(bytes, cursor)? as usize;
167    let end: usize = cursor.saturating_add(len);
168    let slice: &[u8] = bytes
169        .get(*cursor..end)
170        .ok_or_else(|| WasmDynamicError::InvalidWasmBinary("truncated wasm name".to_string()))?;
171    *cursor = end;
172    from_utf8(slice)
173        .map(str::to_string)
174        .map_err(|_| WasmDynamicError::InvalidWasmBinary("non-UTF8 wasm name".to_string()))
175}
176
177/// Parses and validates a standard WebAssembly binary (`.wasm`) into a `WasmParsedModule`.
178///
179/// # Arguments
180///
181/// - `&[u8]` - Raw `.wasm` binary bytes.
182/// - `&WasmSandboxConfig` - Sandbox memory and binary limits enforced during validation.
183///
184/// # Returns
185///
186/// - `Result<WasmParsedModule, WasmDynamicError>` - Validated executable module or typed error.
187pub fn parse_wasm_binary(
188    bytes: &[u8],
189    config: &WasmSandboxConfig,
190) -> Result<WasmParsedModule, WasmDynamicError> {
191    if bytes.len() > config.get_max_binary_bytes() {
192        return Err(WasmDynamicError::BinaryTooLarge {
193            actual: bytes.len(),
194            limit: config.get_max_binary_bytes(),
195        });
196    }
197    if bytes.len() < 8 || &bytes[0..4] != WASM_BINARY_MAGIC || &bytes[4..8] != WASM_BINARY_VERSION {
198        return Err(WasmDynamicError::InvalidWasmBinary(
199            "missing \\0asm v1 header".to_string(),
200        ));
201    }
202    let mut module: WasmParsedModule = WasmParsedModule::default();
203    let mut func_type_indices: Vec<u32> = Vec::new();
204    let mut cursor: usize = 8;
205    while cursor < bytes.len() {
206        let sec_id: u8 = bytes[cursor];
207        cursor += 1;
208        let sec_len: usize = read_uleb128(bytes, &mut cursor)? as usize;
209        let sec_end: usize = cursor.saturating_add(sec_len);
210        if sec_end > bytes.len() {
211            return Err(WasmDynamicError::InvalidWasmBinary(
212                "truncated section payload".to_string(),
213            ));
214        }
215        let sec_slice: &[u8] = &bytes[cursor..sec_end];
216        cursor = sec_end;
217        let mut sc: usize = 0;
218        match sec_id {
219            WASM_SEC_CUSTOM => {
220                let sec_name: String = read_wasm_name(sec_slice, &mut sc)?;
221                let payload: Vec<u8> = sec_slice[sc..].to_vec();
222                let _: Option<Vec<u8>> = module.get_mut_custom_sections().insert(sec_name, payload);
223            }
224            WASM_SEC_TYPE => {
225                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
226                for _ in 0..count {
227                    let tag: u8 = *sec_slice.get(sc).ok_or_else(|| {
228                        WasmDynamicError::InvalidWasmBinary("truncated type entry".to_string())
229                    })?;
230                    sc += 1;
231                    if tag != WASM_FUNCTYPE_TAG {
232                        return Err(WasmDynamicError::InvalidWasmBinary(
233                            "unsupported wasm type tag".to_string(),
234                        ));
235                    }
236                    let params: usize = read_uleb128(sec_slice, &mut sc)? as usize;
237                    sc = sc.saturating_add(params);
238                    let results: usize = read_uleb128(sec_slice, &mut sc)? as usize;
239                    sc = sc.saturating_add(results);
240                    if sc > sec_slice.len() {
241                        return Err(WasmDynamicError::InvalidWasmBinary(
242                            "truncated type signature".to_string(),
243                        ));
244                    }
245                    module
246                        .get_mut_types()
247                        .push(WasmFuncSignature::new(params, results));
248                }
249            }
250            WASM_SEC_IMPORT => {
251                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
252                for _ in 0..count {
253                    let mod_name: String = read_wasm_name(sec_slice, &mut sc)?;
254                    let field_name: String = read_wasm_name(sec_slice, &mut sc)?;
255                    let kind: u8 = *sec_slice.get(sc).ok_or_else(|| {
256                        WasmDynamicError::InvalidWasmBinary("truncated import kind".to_string())
257                    })?;
258                    sc += 1;
259                    if kind == 0x00 {
260                        let type_idx: u32 = read_uleb128(sec_slice, &mut sc)?;
261                        module
262                            .get_mut_imports()
263                            .push(WasmImportEntry::new(mod_name, field_name, type_idx));
264                    } else {
265                        return Err(WasmDynamicError::InvalidWasmBinary(
266                            "unsupported non-function import kind".to_string(),
267                        ));
268                    }
269                }
270            }
271            WASM_SEC_FUNCTION => {
272                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
273                for _ in 0..count {
274                    func_type_indices.push(read_uleb128(sec_slice, &mut sc)?);
275                }
276            }
277            WASM_SEC_MEMORY => {
278                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
279                if count > 0 {
280                    let flags: u8 = *sec_slice.get(sc).ok_or_else(|| {
281                        WasmDynamicError::InvalidWasmBinary("truncated memory limits".to_string())
282                    })?;
283                    sc += 1;
284                    let min_pages: u32 = read_uleb128(sec_slice, &mut sc)?;
285                    if (flags & 0x01) != 0 {
286                        let _: u32 = read_uleb128(sec_slice, &mut sc)?;
287                    }
288                    let req_bytes: usize = (min_pages as usize).saturating_mul(WASM_PAGE_BYTES);
289                    if req_bytes > config.get_max_memory_bytes() {
290                        return Err(WasmDynamicError::MemoryLimitExceeded {
291                            requested: req_bytes,
292                            limit: config.get_max_memory_bytes(),
293                        });
294                    }
295                    module.set_memory_min_pages(min_pages.max(1));
296                }
297            }
298            WASM_SEC_EXPORT => {
299                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
300                for _ in 0..count {
301                    let exp_name: String = read_wasm_name(sec_slice, &mut sc)?;
302                    let kind: u8 = *sec_slice.get(sc).ok_or_else(|| {
303                        WasmDynamicError::InvalidWasmBinary("truncated export kind".to_string())
304                    })?;
305                    sc += 1;
306                    let idx: u32 = read_uleb128(sec_slice, &mut sc)?;
307                    if kind == 0x00 {
308                        let _: Option<u32> = module.get_mut_exports().insert(exp_name, idx);
309                    }
310                }
311            }
312            WASM_SEC_CODE => {
313                let count: usize = read_uleb128(sec_slice, &mut sc)? as usize;
314                if count != func_type_indices.len() {
315                    return Err(WasmDynamicError::InvalidWasmBinary(
316                        "function/code count mismatch".to_string(),
317                    ));
318                }
319                for type_idx in func_type_indices.iter().copied() {
320                    let body_len: usize = read_uleb128(sec_slice, &mut sc)? as usize;
321                    let body_end: usize = sc.saturating_add(body_len);
322                    if body_end > sec_slice.len() {
323                        return Err(WasmDynamicError::InvalidWasmBinary(
324                            "truncated code body".to_string(),
325                        ));
326                    }
327                    let local_decl_groups: u32 = read_uleb128(sec_slice, &mut sc)?;
328                    let mut extra_locals: usize = 0;
329                    for _ in 0..local_decl_groups {
330                        let lcount: usize = read_uleb128(sec_slice, &mut sc)? as usize;
331                        sc = sc.saturating_add(1);
332                        extra_locals = extra_locals.saturating_add(lcount);
333                    }
334                    if sc > body_end {
335                        return Err(WasmDynamicError::InvalidWasmBinary(
336                            "invalid local declarations".to_string(),
337                        ));
338                    }
339                    let code: Vec<u8> = sec_slice[sc..body_end].to_vec();
340                    sc = body_end;
341                    module.get_mut_functions().push(WasmParsedFunction::new(
342                        type_idx,
343                        extra_locals,
344                        code,
345                    ));
346                }
347            }
348            WASM_SEC_DATA => {
349                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
350                for _ in 0..count {
351                    let flags: u32 = read_uleb128(sec_slice, &mut sc)?;
352                    if flags != 0 {
353                        return Err(WasmDynamicError::InvalidWasmBinary(
354                            "unsupported passive data segment".to_string(),
355                        ));
356                    }
357                    let op: u8 = *sec_slice.get(sc).ok_or_else(|| {
358                        WasmDynamicError::InvalidWasmBinary("truncated data offset".to_string())
359                    })?;
360                    sc += 1;
361                    if op != OP_I32_CONST {
362                        return Err(WasmDynamicError::InvalidWasmBinary(
363                            "expected i32.const in data offset".to_string(),
364                        ));
365                    }
366                    let offset: u32 = read_sleb128(sec_slice, &mut sc)?.max(0) as u32;
367                    let end_op: u8 = *sec_slice.get(sc).ok_or_else(|| {
368                        WasmDynamicError::InvalidWasmBinary(
369                            "missing end in data offset".to_string(),
370                        )
371                    })?;
372                    sc += 1;
373                    if end_op != OP_END {
374                        return Err(WasmDynamicError::InvalidWasmBinary(
375                            "malformed data offset expr".to_string(),
376                        ));
377                    }
378                    let data_len: usize = read_uleb128(sec_slice, &mut sc)? as usize;
379                    let data_end: usize = sc.saturating_add(data_len);
380                    if data_end > sec_slice.len() {
381                        return Err(WasmDynamicError::InvalidWasmBinary(
382                            "truncated data segment bytes".to_string(),
383                        ));
384                    }
385                    let seg_bytes: Vec<u8> = sec_slice[sc..data_end].to_vec();
386                    sc = data_end;
387                    module
388                        .get_mut_data_segments()
389                        .push(WasmDataSegment::new(offset, seg_bytes));
390                }
391            }
392            _ => {}
393        }
394    }
395    if module.get_memory_min_pages() == 0 {
396        module.set_memory_min_pages(1);
397    }
398    Ok(module)
399}
400
401/// Reads a bounded UTF-8 slice from WASM linear memory, returning `MemoryOutOfBounds` on invalid ranges.
402///
403/// # Arguments
404///
405/// - `&[u8]` - Active linear memory buffer.
406/// - `u32` - Start pointer offset.
407/// - `u32` - Byte length to read.
408///
409/// # Returns
410///
411/// - `Result<&str, WasmDynamicError>` - Validated UTF-8 slice or memory error.
412fn read_memory_str(memory: &[u8], ptr: u32, len: u32) -> Result<&str, WasmDynamicError> {
413    let start: usize = ptr as usize;
414    let end: usize = start.saturating_add(len as usize);
415    if end > memory.len() {
416        return Err(WasmDynamicError::MemoryOutOfBounds {
417            addr: ptr,
418            len,
419            memory_size: memory.len(),
420        });
421    }
422    from_utf8(&memory[start..end])
423        .map_err(|_| WasmDynamicError::InvalidUiPayload("non-UTF8 memory buffer".to_string()))
424}
425
426/// Executes an exported WebAssembly function inside a fuel-metered, memory-bounded sandbox.
427///
428/// # Arguments
429///
430/// - `&WasmParsedModule` - Validated `.wasm` module.
431/// - `&str` - Exported function name (e.g. `"euv_render"`, `"euv_on_event"`, `"euv_abi_version"`).
432/// - `&[i32]` - Positional `i32` arguments passed to the export.
433/// - `&WasmSandboxConfig` - Fuel and memory limits.
434///
435/// # Returns
436///
437/// - `Result<WasmExecutionOutput, WasmDynamicError>` - Execution output including emitted native UI spec or bundle.
438pub fn execute_wasm_export(
439    module: &WasmParsedModule,
440    export_name: &str,
441    args: &[i32],
442    config: &WasmSandboxConfig,
443) -> Result<WasmExecutionOutput, WasmDynamicError> {
444    let func_idx: u32 = *module
445        .get_exports()
446        .get(export_name)
447        .ok_or_else(|| WasmDynamicError::MissingExport(export_name.to_string()))?;
448    let mem_bytes: usize =
449        (module.get_memory_min_pages().max(1) as usize).saturating_mul(WASM_PAGE_BYTES);
450    if mem_bytes > config.get_max_memory_bytes() {
451        return Err(WasmDynamicError::MemoryLimitExceeded {
452            requested: mem_bytes,
453            limit: config.get_max_memory_bytes(),
454        });
455    }
456    let mut memory: Vec<u8> = vec![0; mem_bytes];
457    for seg in module.get_data_segments().iter() {
458        let start: usize = seg.get_offset() as usize;
459        let end: usize = start.saturating_add(seg.get_bytes().len());
460        if end > memory.len() {
461            return Err(WasmDynamicError::MemoryOutOfBounds {
462                addr: seg.get_offset(),
463                len: seg.get_bytes().len() as u32,
464                memory_size: memory.len(),
465            });
466        }
467        memory[start..end].copy_from_slice(seg.get_bytes().as_slice());
468    }
469    let mut out: WasmExecutionOutput = WasmExecutionOutput::default();
470    let mut exec: WasmExecContext<'_> = WasmExecContext {
471        memory: &mut memory,
472        out: &mut out,
473        fuel_used: 0,
474        max_fuel: config.get_max_fuel(),
475        depth: 0,
476    };
477    let ret: i32 = execute_wasm_func_index(module, func_idx, args, &mut exec)?;
478    let fuel_used: u64 = exec.fuel_used;
479    out.set_return_value(ret);
480    out.set_fuel_used(fuel_used);
481    Ok(out)
482}
483
484/// Evaluates an `i32` binary WebAssembly opcode if `op` matches one.
485///
486/// # Arguments
487///
488/// - `u8` - Bytecode opcode.
489/// - `&mut Vec<i32>` - Active operand stack.
490///
491/// # Returns
492///
493/// - `Result<Option<i32>, WasmDynamicError>` - Computed result if `op` is a supported binop, `None` otherwise.
494fn eval_i32_binop(op: u8, stack: &mut Vec<i32>) -> Result<Option<i32>, WasmDynamicError> {
495    let is_binop: bool = op == OP_I32_EQ
496        || op == OP_I32_NE
497        || op == OP_I32_LT_S
498        || op == OP_I32_GT_S
499        || op == OP_I32_ADD
500        || op == OP_I32_SUB
501        || op == OP_I32_MUL
502        || op == OP_I32_DIV_S;
503    if !is_binop {
504        return Ok(None);
505    }
506    let b: i32 = stack
507        .pop()
508        .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
509    let a: i32 = stack
510        .pop()
511        .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
512    let res: i32 = match op {
513        OP_I32_EQ => i32::from(a == b),
514        OP_I32_NE => i32::from(a != b),
515        OP_I32_LT_S => i32::from(a < b),
516        OP_I32_GT_S => i32::from(a > b),
517        OP_I32_ADD => a.wrapping_add(b),
518        OP_I32_SUB => a.wrapping_sub(b),
519        OP_I32_MUL => a.wrapping_mul(b),
520        OP_I32_DIV_S => {
521            if b == 0 {
522                return Err(WasmDynamicError::ExecutionTrap(
523                    "integer divide by zero".to_string(),
524                ));
525            }
526            a.wrapping_div(b)
527        }
528        _ => 0,
529    };
530    Ok(Some(res))
531}
532
533/// Internal recursive bytecode interpreter executing a single WASM function or host import call.
534///
535/// # Arguments
536///
537/// - `&WasmParsedModule` - Active parsed module.
538/// - `u32` - Absolute function index (imports first, then defined functions).
539/// - `&[i32]` - Call arguments.
540/// - `&mut WasmExecContext<'_>` - Shared mutable memory, host output, fuel, and depth state.
541///
542/// # Returns
543///
544/// - `Result<i32, WasmDynamicError>` - Return value or sandbox error.
545fn execute_wasm_func_index(
546    module: &WasmParsedModule,
547    func_idx: u32,
548    args: &[i32],
549    exec: &mut WasmExecContext<'_>,
550) -> Result<i32, WasmDynamicError> {
551    if exec.depth > 32 {
552        return Err(WasmDynamicError::ExecutionTrap(
553            "call stack depth overflow".to_string(),
554        ));
555    }
556    let import_count: usize = module.get_imports().len();
557    if (func_idx as usize) < import_count {
558        let imp: &WasmImportEntry = &module.get_imports()[func_idx as usize];
559        let ptr: u32 = args.first().copied().unwrap_or(0).max(0) as u32;
560        let len: u32 = args.get(1).copied().unwrap_or(0).max(0) as u32;
561        let text: &str = read_memory_str(exec.memory, ptr, len)?;
562        if imp.get_name() == WASM_IMPORT_EMIT_UI {
563            let spec: DynamicNodeSpec =
564                from_str::<DynamicNodeSpec>(text).map_err(|err: serde_json::Error| {
565                    WasmDynamicError::InvalidUiPayload(err.to_string())
566                })?;
567            exec.out.set_emitted_spec(Some(spec));
568            return Ok(1);
569        }
570        if imp.get_name() == WASM_IMPORT_EMIT_BUNDLE {
571            let bundle: DynamicUpdateBundle =
572                from_str::<DynamicUpdateBundle>(text).map_err(|err: serde_json::Error| {
573                    WasmDynamicError::InvalidUiPayload(err.to_string())
574                })?;
575            exec.out.set_emitted_bundle(Some(bundle));
576            return Ok(1);
577        }
578        if imp.get_name() == WASM_IMPORT_LOG {
579            exec.out.get_mut_logs().push(text.to_string());
580            return Ok(1);
581        }
582        return Err(WasmDynamicError::ExecutionTrap(format!(
583            "unknown host import {}::{}",
584            imp.get_module(),
585            imp.get_name()
586        )));
587    }
588    let local_idx: usize = (func_idx as usize) - import_count;
589    let func: &WasmParsedFunction = module
590        .get_functions()
591        .get(local_idx)
592        .ok_or_else(|| WasmDynamicError::ExecutionTrap("invalid function index".to_string()))?;
593    let sig: WasmFuncSignature = module
594        .get_types()
595        .get(func.get_type_index() as usize)
596        .copied()
597        .unwrap_or_default();
598    let total_locals: usize = sig
599        .get_param_count()
600        .saturating_add(func.get_extra_locals());
601    let mut locals: Vec<i32> = vec![0; total_locals.max(args.len())];
602    for (idx, val) in args.iter().copied().enumerate() {
603        if idx < locals.len() {
604            locals[idx] = val;
605        }
606    }
607    let code: &[u8] = func.get_body().as_slice();
608    let mut stack: Vec<i32> = Vec::with_capacity(32);
609    let mut labels: Vec<(u8, usize)> = Vec::with_capacity(16);
610    let mut pc: usize = 0;
611    while pc < code.len() {
612        exec.fuel_used = exec.fuel_used.saturating_add(1);
613        if exec.fuel_used > exec.max_fuel {
614            return Err(WasmDynamicError::OutOfFuel {
615                limit: exec.max_fuel,
616            });
617        }
618        let op: u8 = code[pc];
619        pc += 1;
620        match op {
621            OP_UNREACHABLE => {
622                return Err(WasmDynamicError::ExecutionTrap(
623                    "wasm unreachable instruction trapped".to_string(),
624                ));
625            }
626            OP_NOP => {}
627            OP_BLOCK | OP_LOOP => {
628                let _: u8 = *code.get(pc).unwrap_or(&0x40);
629                pc = pc.saturating_add(1);
630                labels.push((op, pc));
631            }
632            OP_IF => {
633                let _: u8 = *code.get(pc).unwrap_or(&0x40);
634                pc = pc.saturating_add(1);
635                let cond: i32 = stack.pop().ok_or_else(|| {
636                    WasmDynamicError::ExecutionTrap("stack underflow on if".to_string())
637                })?;
638                if cond != 0 {
639                    labels.push((OP_IF, pc));
640                } else {
641                    let mut nesting: usize = 0;
642                    while pc < code.len() {
643                        let scan: u8 = code[pc];
644                        pc += 1;
645                        if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
646                            nesting += 1;
647                            pc = pc.saturating_add(1);
648                        } else if scan == OP_ELSE && nesting == 0 {
649                            labels.push((OP_ELSE, pc));
650                            break;
651                        } else if scan == OP_END {
652                            if nesting == 0 {
653                                break;
654                            }
655                            nesting -= 1;
656                        } else if scan == OP_I32_CONST {
657                            let _: i32 = read_sleb128(code, &mut pc)?;
658                        } else if scan == OP_LOCAL_GET
659                            || scan == OP_LOCAL_SET
660                            || scan == OP_CALL
661                            || scan == OP_BR
662                            || scan == OP_BR_IF
663                        {
664                            let _: u32 = read_uleb128(code, &mut pc)?;
665                        } else if scan == OP_I32_LOAD || scan == OP_I32_STORE {
666                            let _: u32 = read_uleb128(code, &mut pc)?;
667                            let _: u32 = read_uleb128(code, &mut pc)?;
668                        }
669                    }
670                }
671            }
672            OP_ELSE => {
673                let _: Option<(u8, usize)> = labels.pop();
674                let mut nesting: usize = 0;
675                while pc < code.len() {
676                    let scan: u8 = code[pc];
677                    pc += 1;
678                    if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
679                        nesting += 1;
680                        pc = pc.saturating_add(1);
681                    } else if scan == OP_END {
682                        if nesting == 0 {
683                            break;
684                        }
685                        nesting -= 1;
686                    } else if scan == OP_I32_CONST {
687                        let _: i32 = read_sleb128(code, &mut pc)?;
688                    } else if scan == OP_LOCAL_GET
689                        || scan == OP_LOCAL_SET
690                        || scan == OP_CALL
691                        || scan == OP_BR
692                        || scan == OP_BR_IF
693                    {
694                        let _: u32 = read_uleb128(code, &mut pc)?;
695                    } else if scan == OP_I32_LOAD || scan == OP_I32_STORE {
696                        let _: u32 = read_uleb128(code, &mut pc)?;
697                        let _: u32 = read_uleb128(code, &mut pc)?;
698                    }
699                }
700            }
701            OP_END => {
702                if labels.pop().is_none() {
703                    break;
704                }
705            }
706            OP_BR | OP_BR_IF => {
707                let target_depth: usize = read_uleb128(code, &mut pc)? as usize;
708                let take_branch: bool = if op == OP_BR_IF {
709                    stack.pop().unwrap_or(0) != 0
710                } else {
711                    true
712                };
713                if take_branch {
714                    if target_depth >= labels.len() {
715                        break;
716                    }
717                    let keep_len: usize = labels.len() - target_depth;
718                    let (lbl_op, lbl_pc): (u8, usize) = labels[keep_len - 1];
719                    if lbl_op == OP_LOOP {
720                        labels.truncate(keep_len);
721                        pc = lbl_pc;
722                    } else {
723                        labels.truncate(keep_len - 1);
724                        let mut nesting: usize = 0;
725                        while pc < code.len() {
726                            let scan: u8 = code[pc];
727                            pc += 1;
728                            if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
729                                nesting += 1;
730                                pc = pc.saturating_add(1);
731                            } else if scan == OP_END {
732                                if nesting == 0 {
733                                    break;
734                                }
735                                nesting -= 1;
736                            }
737                        }
738                    }
739                }
740            }
741            OP_RETURN => break,
742            OP_CALL => {
743                let callee: u32 = read_uleb128(code, &mut pc)?;
744                let callee_type: u32 = if (callee as usize) < import_count {
745                    module.get_imports()[callee as usize].get_type_index()
746                } else {
747                    module
748                        .get_functions()
749                        .get((callee as usize) - import_count)
750                        .map(WasmParsedFunction::get_type_index)
751                        .unwrap_or(0)
752                };
753                let csig: WasmFuncSignature = module
754                    .get_types()
755                    .get(callee_type as usize)
756                    .copied()
757                    .unwrap_or_default();
758                let mut call_args: Vec<i32> = vec![0; csig.get_param_count()];
759                for idx in (0..csig.get_param_count()).rev() {
760                    call_args[idx] = stack.pop().ok_or_else(|| {
761                        WasmDynamicError::ExecutionTrap("stack underflow on call".to_string())
762                    })?;
763                }
764                exec.depth = exec.depth.saturating_add(1);
765                let call_res: Result<i32, WasmDynamicError> =
766                    execute_wasm_func_index(module, callee, call_args.as_slice(), exec);
767                exec.depth = exec.depth.saturating_sub(1);
768                let call_ret: i32 = call_res?;
769                if csig.get_result_count() > 0 {
770                    stack.push(call_ret);
771                }
772            }
773            OP_DROP => {
774                let _: Option<i32> = stack.pop();
775            }
776            OP_LOCAL_GET => {
777                let idx: usize = read_uleb128(code, &mut pc)? as usize;
778                let val: i32 = *locals.get(idx).unwrap_or(&0);
779                stack.push(val);
780            }
781            OP_LOCAL_SET => {
782                let idx: usize = read_uleb128(code, &mut pc)? as usize;
783                let val: i32 = stack.pop().ok_or_else(|| {
784                    WasmDynamicError::ExecutionTrap("stack underflow on local.set".to_string())
785                })?;
786                if idx < locals.len() {
787                    locals[idx] = val;
788                }
789            }
790            OP_I32_LOAD => {
791                let _: u32 = read_uleb128(code, &mut pc)?;
792                let offset: u32 = read_uleb128(code, &mut pc)?;
793                let base: u32 = stack.pop().unwrap_or(0).max(0) as u32;
794                let addr: usize = (base.saturating_add(offset)) as usize;
795                if addr.saturating_add(4) > exec.memory.len() {
796                    return Err(WasmDynamicError::MemoryOutOfBounds {
797                        addr: addr as u32,
798                        len: 4,
799                        memory_size: exec.memory.len(),
800                    });
801                }
802                let val: i32 = i32::from_le_bytes([
803                    exec.memory[addr],
804                    exec.memory[addr + 1],
805                    exec.memory[addr + 2],
806                    exec.memory[addr + 3],
807                ]);
808                stack.push(val);
809            }
810            OP_I32_STORE => {
811                let _: u32 = read_uleb128(code, &mut pc)?;
812                let offset: u32 = read_uleb128(code, &mut pc)?;
813                let val: i32 = stack.pop().unwrap_or(0);
814                let base: u32 = stack.pop().unwrap_or(0).max(0) as u32;
815                let addr: usize = (base.saturating_add(offset)) as usize;
816                if addr.saturating_add(4) > exec.memory.len() {
817                    return Err(WasmDynamicError::MemoryOutOfBounds {
818                        addr: addr as u32,
819                        len: 4,
820                        memory_size: exec.memory.len(),
821                    });
822                }
823                exec.memory[addr..addr + 4].copy_from_slice(&val.to_le_bytes());
824            }
825            OP_I32_CONST => {
826                let val: i32 = read_sleb128(code, &mut pc)?;
827                stack.push(val);
828            }
829            OP_I32_EQZ => {
830                let a: i32 = stack.pop().unwrap_or(0);
831                stack.push(if a == 0 { 1 } else { 0 });
832            }
833            other => {
834                if let Some(res) = eval_i32_binop(other, &mut stack)? {
835                    stack.push(res);
836                } else {
837                    return Err(WasmDynamicError::ExecutionTrap(format!(
838                        "unsupported wasm opcode 0x{other:02x}"
839                    )));
840                }
841            }
842        }
843    }
844    Ok(stack.pop().unwrap_or(0))
845}
846
847/// Builds a genuine signed partial-slot `.wasm` binary rendering a rich native `DynamicNodeSpec` with live interactive state.
848///
849/// # Arguments
850///
851/// - `&str` - Display title rendered by the WASM widget.
852/// - `u64` - Release version number.
853/// - `u32` - Accent RGB hex color.
854///
855/// # Returns
856///
857/// - `Vec<u8>` - Spec-compliant executable `.wasm` binary bytes.
858#[must_use]
859pub fn build_partial_widget_wasm(title: &str, version: u64, accent_hex: u32) -> Vec<u8> {
860    let mut badge: DynamicNodeSpec = DynamicNodeSpec::badge(format!("WASM v{version} · NATIVE"));
861    badge
862        .get_mut_style()
863        .set_background_hex(Some(accent_hex))
864        .set_color_hex(Some(0xFFFFFF));
865    let mut heading: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
866    heading
867        .get_mut_style()
868        .set_bold(true)
869        .set_font_size(Some(14.0));
870    let sub: DynamicNodeSpec = DynamicNodeSpec::text(format!(
871        "Downloaded .wasm binary executed in sandboxed VM and rendered directly to native SceneTree (rev v{version}, state=0)."
872    ));
873    let mut btn_interact: DynamicNodeSpec = DynamicNodeSpec::button(
874        "Invoke WASM euv_on_event (+1)".to_string(),
875        "wasm_interact".to_string(),
876    );
877    btn_interact.get_mut_style().set_full_width(true);
878    btn_interact.set_payload(format!("wasm-partial-v{version}"));
879    let mut root_even: DynamicNodeSpec = DynamicNodeSpec::column()
880        .child(
881            DynamicNodeSpec::row()
882                .child(badge.clone())
883                .child(heading.clone()),
884        )
885        .child(sub)
886        .child(btn_interact.clone());
887    root_even
888        .get_mut_style()
889        .set_full_width(true)
890        .set_padding(Some(14.0))
891        .set_gap(Some(10.0))
892        .set_radius(Some(10.0))
893        .set_border_width(Some(1.0))
894        .set_border_hex(Some(accent_hex));
895    let sub_alt: DynamicNodeSpec = DynamicNodeSpec::text(format!(
896        "Interactive WASM state toggled inside sandbox (rev v{version}, active pulse state=1) — zero host rebuild!"
897    ));
898    let mut root_odd: DynamicNodeSpec = DynamicNodeSpec::column()
899        .child(DynamicNodeSpec::row().child(badge).child(heading))
900        .child(sub_alt)
901        .child(btn_interact);
902    root_odd
903        .get_mut_style()
904        .set_full_width(true)
905        .set_padding(Some(14.0))
906        .set_gap(Some(10.0))
907        .set_radius(Some(10.0))
908        .set_background_hex(Some(0xECFDF5))
909        .set_border_width(Some(1.0))
910        .set_border_hex(Some(0x10B981));
911    WasmModuleBuilder::partial_spec(&root_even)
912        .with_alt_spec(&root_odd)
913        .with_log(format!("partial wasm v{version} rendered natively"))
914        .build()
915}
916
917/// Builds one deterministic state bundle (`state_idx = 0 | 1`) embedded inside a global full-app `.wasm` release.
918///
919/// # Arguments
920///
921/// - `&str` - Global release title.
922/// - `u64` - Monotonic global release version.
923/// - `u8` - Interactive toggle state index (`0` or `1`).
924///
925/// # Returns
926///
927/// - `DynamicUpdateBundle` - Signed bundle targeting both global root component and page routes.
928#[must_use]
929fn build_global_state_bundle(title: &str, version: u64, state_idx: u8) -> DynamicUpdateBundle {
930    let mut badge: DynamicNodeSpec =
931        DynamicNodeSpec::badge(format!("GLOBAL WASM APP v{version} · STATE #{state_idx}"));
932    badge
933        .get_mut_style()
934        .set_background_hex(Some(if state_idx == 0 { 0x0F766E } else { 0x1D4ED8 }))
935        .set_color_hex(Some(0xFFFFFF));
936    let mut hero_title: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
937    hero_title
938        .get_mut_style()
939        .set_bold(true)
940        .set_font_size(Some(20.0));
941    let hero_sub: DynamicNodeSpec = DynamicNodeSpec::text(if state_idx == 0 {
942        format!(
943            "Entire native UI shell hot-replaced atomically from downloaded global .wasm release v{version}. Tap any button below to invoke sandboxed WASM events or return."
944        )
945    } else {
946        format!(
947            "Global WASM euv_on_event executed live inside sandbox (v{version}, active pulse state=1)! Zero restart — tap Restore Native Shell anytime to roll back."
948        )
949    });
950    let mut kpi_col: DynamicNodeSpec =
951        DynamicNodeSpec::column()
952            .child(DynamicNodeSpec::card("Execution Mode".to_string()).child(
953                DynamicNodeSpec::text("Sandboxed WASM -> Native SceneTree".to_string()),
954            ))
955            .child(
956                DynamicNodeSpec::card("Integrity Gate".to_string())
957                    .child(DynamicNodeSpec::text(format!("Verified Signed v{version}"))),
958            )
959            .child(
960                DynamicNodeSpec::card("Safety Guard".to_string()).child(DynamicNodeSpec::text(
961                    "Fuel + Memory + Atomic LKG Rollback".to_string(),
962                )),
963            );
964    kpi_col
965        .get_mut_style()
966        .set_full_width(true)
967        .set_gap(Some(10.0));
968    let mut btn_action: DynamicNodeSpec = DynamicNodeSpec::button(
969        "Invoke Global WASM Action (+1)".to_string(),
970        "global_wasm_action".to_string(),
971    );
972    btn_action.get_mut_style().set_full_width(true);
973    btn_action.set_payload(format!("global-v{version}-state-{state_idx}"));
974    let mut btn_rollback: DynamicNodeSpec = DynamicNodeSpec::button(
975        "Rollback Previous Version".to_string(),
976        "global_wasm_rollback".to_string(),
977    );
978    btn_rollback
979        .get_mut_style()
980        .set_full_width(true)
981        .set_background_hex(Some(0x334155))
982        .set_color_hex(Some(0xFFFFFF));
983    btn_rollback.set_payload("rollback-global".to_string());
984    let mut btn_restore: DynamicNodeSpec = DynamicNodeSpec::button(
985        "Return to Native Shell".to_string(),
986        "global_wasm_restore".to_string(),
987    );
988    btn_restore
989        .get_mut_style()
990        .set_full_width(true)
991        .set_background_hex(Some(0x0F766E))
992        .set_color_hex(Some(0xFFFFFF));
993    btn_restore.set_payload("restore-native".to_string());
994    let mut action_row: DynamicNodeSpec = DynamicNodeSpec::column()
995        .child(btn_action)
996        .child(btn_rollback)
997        .child(btn_restore);
998    action_row
999        .get_mut_style()
1000        .set_full_width(true)
1001        .set_gap(Some(10.0));
1002    let mut root_spec: DynamicNodeSpec = DynamicNodeSpec::column()
1003        .child(badge)
1004        .child(hero_title)
1005        .child(hero_sub)
1006        .child(action_row)
1007        .child(kpi_col);
1008    root_spec
1009        .get_mut_style()
1010        .set_full_width(true)
1011        .set_padding(Some(20.0))
1012        .set_gap(Some(14.0))
1013        .set_radius(Some(12.0))
1014        .set_background_hex(Some(if state_idx == 0 { 0xFFFFFF } else { 0xEFF6FF }))
1015        .set_border_width(Some(1.0))
1016        .set_border_hex(Some(if state_idx == 0 { 0x14B8A6 } else { 0x2563EB }));
1017    let mut global_comp: DynamicComponentUpdate = DynamicComponentUpdate::new(
1018        WASM_GLOBAL_ROOT_SLOT.to_string(),
1019        version,
1020        root_spec.clone(),
1021    );
1022    global_comp.set_allow_downgrade(true);
1023    global_comp.sign();
1024    let mut global_page: DynamicPageUpdate = DynamicPageUpdate::new(
1025        "/wasm-global-live".to_string(),
1026        format!("Global WASM v{version}"),
1027        version,
1028        root_spec,
1029    );
1030    global_page.set_allow_downgrade(true);
1031    global_page.sign();
1032    let mut bundle: DynamicUpdateBundle =
1033        DynamicUpdateBundle::new(format!("global-wasm-v{version}"), version);
1034    bundle.get_mut_components().push(global_comp);
1035    bundle.get_mut_pages().push(global_page);
1036    bundle
1037}
1038
1039/// Builds a genuine global full-app `.wasm` binary emitting a complete `DynamicUpdateBundle` that atomically takes over the root shell.
1040///
1041/// # Arguments
1042///
1043/// - `&str` - Global release title.
1044/// - `u64` - Monotonic global release version.
1045///
1046/// # Returns
1047///
1048/// - `Vec<u8>` - Spec-compliant executable global `.wasm` binary bytes.
1049#[must_use]
1050pub fn build_global_app_wasm(title: &str, version: u64) -> Vec<u8> {
1051    let bundle_even: DynamicUpdateBundle = build_global_state_bundle(title, version, 0);
1052    let bundle_odd: DynamicUpdateBundle = build_global_state_bundle(title, version, 1);
1053    WasmModuleBuilder::global_bundle(&bundle_even)
1054        .with_alt_bundle(&bundle_odd)
1055        .with_log(format!("global wasm bundle v{version} mounted natively"))
1056        .build()
1057}
1058
1059/// Builds a faulty `.wasm` binary exercising a specific security, integrity, ABI, or sandbox trap case.
1060///
1061/// # Arguments
1062///
1063/// - `WasmFaultKind` - Specific failure case to compile into the test binary.
1064///
1065/// # Returns
1066///
1067/// - `Vec<u8>` - Crafted `.wasm` binary bytes triggering `fault`.
1068#[must_use]
1069pub fn build_faulty_wasm(fault: WasmFaultKind) -> Vec<u8> {
1070    match fault {
1071        WasmFaultKind::CorruptedMagic => b"NOT_A_VALID_WASM_BINARY".to_vec(),
1072        WasmFaultKind::AbiMismatch => {
1073            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Incompatible ABI".to_string()))
1074                .with_abi_version(99)
1075                .build()
1076        }
1077        WasmFaultKind::MissingExport => {
1078            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Missing Export".to_string()))
1079                .without_render_export()
1080                .build()
1081        }
1082        WasmFaultKind::InfiniteLoopOutOfFuel => {
1083            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Infinite Loop".to_string()))
1084                .with_fault(WasmFaultKind::InfiniteLoopOutOfFuel)
1085                .build()
1086        }
1087        WasmFaultKind::ExecutionTrap => {
1088            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Trap".to_string()))
1089                .with_fault(WasmFaultKind::ExecutionTrap)
1090                .build()
1091        }
1092        WasmFaultKind::OversizedBinary => {
1093            let mut big: Vec<u8> = build_partial_widget_wasm("Oversized", 1, 0xDC2626);
1094            big.resize(WASM_DEFAULT_MAX_BINARY_BYTES + 64, 0);
1095            big
1096        }
1097        _ => build_partial_widget_wasm("Fault Fixture", 1, 0x2563EB),
1098    }
1099}