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]
13#[inline]
14pub fn compute_wasm_checksum(bytes: &[u8]) -> u64 {
15    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
16    const FNV_PRIME: u64 = 0x0100_0000_01b3;
17    let mut hash: u64 = FNV_OFFSET;
18    let mut slice: &[u8] = bytes;
19    while let Some((chunk, rest)) = slice.split_first_chunk::<8>() {
20        hash = (hash ^ (chunk[0] as u64)).wrapping_mul(FNV_PRIME);
21        hash = (hash ^ (chunk[1] as u64)).wrapping_mul(FNV_PRIME);
22        hash = (hash ^ (chunk[2] as u64)).wrapping_mul(FNV_PRIME);
23        hash = (hash ^ (chunk[3] as u64)).wrapping_mul(FNV_PRIME);
24        hash = (hash ^ (chunk[4] as u64)).wrapping_mul(FNV_PRIME);
25        hash = (hash ^ (chunk[5] as u64)).wrapping_mul(FNV_PRIME);
26        hash = (hash ^ (chunk[6] as u64)).wrapping_mul(FNV_PRIME);
27        hash = (hash ^ (chunk[7] as u64)).wrapping_mul(FNV_PRIME);
28        slice = rest;
29    }
30    for byte in slice.iter().copied() {
31        hash = (hash ^ (byte as u64)).wrapping_mul(FNV_PRIME);
32    }
33    hash.max(1)
34}
35
36/// Computes a deterministic keyed integrity signature tag for a `.wasm` binary and release version.
37///
38/// # Arguments
39///
40/// - `&[u8]` - Raw `.wasm` binary bytes.
41/// - `u64` - Release version number.
42/// - `&str` - Shared verification key or signing secret.
43///
44/// # Returns
45///
46/// - `String` - Formatted signature tag (`"euv-sig-v1:<hex>"`).
47#[must_use]
48pub fn compute_wasm_signature(bytes: &[u8], version: u64, signing_key: &str) -> String {
49    const FNV_PRIME: u64 = 0x0100_0000_01b3;
50    const SIG_MIX: u64 = 0x517c_c1b7_2722_0a95;
51    let mut h1: u64 = 0xcbf2_9ce4_8422_2325 ^ version.wrapping_mul(0x9E37_79B9_7F4A_7C15);
52    let mut h2: u64 = 0x8422_2325_cbf2_9ce4 ^ (bytes.len() as u64);
53    for byte in signing_key.as_bytes().iter().copied() {
54        let blue_val: u64 = byte as u64;
55        h1 = (h1 ^ blue_val).wrapping_mul(FNV_PRIME);
56        h2 = h2.rotate_left(7) ^ blue_val;
57    }
58    let mut slice: &[u8] = bytes;
59    while let Some((chunk, rest)) = slice.split_first_chunk::<4>() {
60        let b0: u64 = chunk[0] as u64;
61        h1 = (h1 ^ b0).wrapping_mul(FNV_PRIME);
62        h2 = (h2 ^ b0.wrapping_mul(SIG_MIX)).rotate_left(13);
63        let b1: u64 = chunk[1] as u64;
64        h1 = (h1 ^ b1).wrapping_mul(FNV_PRIME);
65        h2 = (h2 ^ b1.wrapping_mul(SIG_MIX)).rotate_left(13);
66        let b2: u64 = chunk[2] as u64;
67        h1 = (h1 ^ b2).wrapping_mul(FNV_PRIME);
68        h2 = (h2 ^ b2.wrapping_mul(SIG_MIX)).rotate_left(13);
69        let b3: u64 = chunk[3] as u64;
70        h1 = (h1 ^ b3).wrapping_mul(FNV_PRIME);
71        h2 = (h2 ^ b3.wrapping_mul(SIG_MIX)).rotate_left(13);
72        slice = rest;
73    }
74    for byte in slice.iter().copied() {
75        let byte_val: u64 = byte as u64;
76        h1 = (h1 ^ byte_val).wrapping_mul(FNV_PRIME);
77        h2 = (h2 ^ byte_val.wrapping_mul(SIG_MIX)).rotate_left(13);
78    }
79    format!("{WASM_SIGNATURE_PREFIX}{h1:016x}{h2:016x}")
80}
81
82/// Encodes an unsigned 32-bit integer as LEB128 into `out`.
83///
84/// # Arguments
85///
86/// - `&mut Vec<u8>` - Destination byte vector.
87/// - `u32` - Unsigned integer to encode.
88pub(crate) fn write_uleb128(out: &mut Vec<u8>, mut value: u32) {
89    loop {
90        let mut byte: u8 = (value & 0x7F) as u8;
91        value >>= 7;
92        if value != 0 {
93            byte |= 0x80;
94        }
95        out.push(byte);
96        if value == 0 {
97            break;
98        }
99    }
100}
101
102/// Encodes a signed 32-bit integer as SLEB128 into `out`.
103///
104/// # Arguments
105///
106/// - `&mut Vec<u8>` - Destination byte vector.
107/// - `i32` - Signed integer to encode.
108pub(crate) fn write_sleb128(out: &mut Vec<u8>, mut value: i32) {
109    loop {
110        let byte: u8 = (value & 0x7F) as u8;
111        value >>= 7;
112        let done: bool = (value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0);
113        if done {
114            out.push(byte);
115            break;
116        }
117        out.push(byte | 0x80);
118    }
119}
120
121/// Decodes an unsigned 32-bit LEB128 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<u32, WasmDynamicError>` - Decoded integer or `InvalidWasmBinary`.
131pub(crate) fn read_uleb128(bytes: &[u8], cursor: &mut usize) -> Result<u32, WasmDynamicError> {
132    let mut result: u32 = 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 uleb128".to_string())
137        })?;
138        *cursor += 1;
139        if shift >= 35 {
140            return Err(WasmDynamicError::InvalidWasmBinary(
141                "uleb128 integer overflow".to_string(),
142            ));
143        }
144        result |= ((byte & 0x7F) as u32).wrapping_shl(shift);
145        if (byte & 0x80) == 0 {
146            return Ok(result);
147        }
148        shift += 7;
149    }
150}
151
152/// Decodes a signed 32-bit SLEB128 integer starting at `*cursor` in `bytes`.
153///
154/// # Arguments
155///
156/// - `&[u8]` - Source WASM byte slice.
157/// - `&mut usize` - Read cursor advanced past the encoded integer.
158///
159/// # Returns
160///
161/// - `Result<i32, WasmDynamicError>` - Decoded signed integer or `InvalidWasmBinary`.
162pub(crate) fn read_sleb128(bytes: &[u8], cursor: &mut usize) -> Result<i32, WasmDynamicError> {
163    let mut result: i32 = 0;
164    let mut shift: u32 = 0;
165    loop {
166        let byte: u8 = *bytes.get(*cursor).ok_or_else(|| {
167            WasmDynamicError::InvalidWasmBinary("unexpected EOF in sleb128".to_string())
168        })?;
169        *cursor += 1;
170        if shift >= 35 {
171            return Err(WasmDynamicError::InvalidWasmBinary(
172                "sleb128 integer overflow".to_string(),
173            ));
174        }
175        result |= ((byte & 0x7F) as i32).wrapping_shl(shift);
176        shift += 7;
177        if (byte & 0x80) == 0 {
178            if shift < 32 && (byte & 0x40) != 0 {
179                result |= !0_i32 << shift;
180            }
181            return Ok(result);
182        }
183    }
184}
185
186/// Reads a length-prefixed UTF-8 WebAssembly name string from `bytes`.
187///
188/// # Arguments
189///
190/// - `&[u8]` - Source WASM byte slice.
191/// - `&mut usize` - Read cursor advanced past the string.
192///
193/// # Returns
194///
195/// - `Result<String, WasmDynamicError>` - Decoded UTF-8 identifier or `InvalidWasmBinary`.
196fn read_wasm_name(bytes: &[u8], cursor: &mut usize) -> Result<String, WasmDynamicError> {
197    let len: usize = read_uleb128(bytes, cursor)? as usize;
198    let end: usize = cursor.saturating_add(len);
199    let slice: &[u8] = bytes
200        .get(*cursor..end)
201        .ok_or_else(|| WasmDynamicError::InvalidWasmBinary("truncated wasm name".to_string()))?;
202    *cursor = end;
203    from_utf8(slice)
204        .map(str::to_string)
205        .map_err(|_| WasmDynamicError::InvalidWasmBinary("non-UTF8 wasm name".to_string()))
206}
207
208/// Parses and validates a standard WebAssembly binary (`.wasm`) into a `WasmParsedModule`.
209///
210/// # Arguments
211///
212/// - `&[u8]` - Raw `.wasm` binary bytes.
213/// - `&WasmSandboxConfig` - Sandbox memory and binary limits enforced during validation.
214///
215/// # Returns
216///
217/// - `Result<WasmParsedModule, WasmDynamicError>` - Validated executable module or typed error.
218pub fn parse_wasm_binary(
219    bytes: &[u8],
220    config: &WasmSandboxConfig,
221) -> Result<WasmParsedModule, WasmDynamicError> {
222    if bytes.len() > config.get_max_binary_bytes() {
223        return Err(WasmDynamicError::BinaryTooLarge {
224            actual: bytes.len(),
225            limit: config.get_max_binary_bytes(),
226        });
227    }
228    if bytes.len() < 8 || &bytes[0..4] != WASM_BINARY_MAGIC || &bytes[4..8] != WASM_BINARY_VERSION {
229        return Err(WasmDynamicError::InvalidWasmBinary(
230            "missing \\0asm v1 header".to_string(),
231        ));
232    }
233    let mut module: WasmParsedModule = WasmParsedModule::default();
234    let mut func_type_indices: Vec<u32> = Vec::new();
235    let mut cursor: usize = 8;
236    while cursor < bytes.len() {
237        let sec_id: u8 = bytes[cursor];
238        cursor += 1;
239        let sec_len: usize = read_uleb128(bytes, &mut cursor)? as usize;
240        let sec_end: usize = cursor.saturating_add(sec_len);
241        if sec_end > bytes.len() {
242            return Err(WasmDynamicError::InvalidWasmBinary(
243                "truncated section payload".to_string(),
244            ));
245        }
246        let sec_slice: &[u8] = &bytes[cursor..sec_end];
247        cursor = sec_end;
248        let mut scale_factor: usize = 0;
249        match sec_id {
250            WASM_SEC_CUSTOM => {
251                let sec_name: String = read_wasm_name(sec_slice, &mut scale_factor)?;
252                let payload: Vec<u8> = sec_slice[scale_factor..].to_vec();
253                let _: Option<Vec<u8>> = module.get_mut_custom_sections().insert(sec_name, payload);
254            }
255            WASM_SEC_TYPE => {
256                let count: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
257                for _ in 0..count {
258                    let tag: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
259                        WasmDynamicError::InvalidWasmBinary("truncated type entry".to_string())
260                    })?;
261                    scale_factor += 1;
262                    if tag != WASM_FUNCTYPE_TAG {
263                        return Err(WasmDynamicError::InvalidWasmBinary(
264                            "unsupported wasm type tag".to_string(),
265                        ));
266                    }
267                    let params: usize = read_uleb128(sec_slice, &mut scale_factor)? as usize;
268                    scale_factor = scale_factor.saturating_add(params);
269                    let results: usize = read_uleb128(sec_slice, &mut scale_factor)? as usize;
270                    scale_factor = scale_factor.saturating_add(results);
271                    if scale_factor > sec_slice.len() {
272                        return Err(WasmDynamicError::InvalidWasmBinary(
273                            "truncated type signature".to_string(),
274                        ));
275                    }
276                    module
277                        .get_mut_types()
278                        .push(WasmFuncSignature::new(params, results));
279                }
280            }
281            WASM_SEC_IMPORT => {
282                let count: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
283                for _ in 0..count {
284                    let mod_name: String = read_wasm_name(sec_slice, &mut scale_factor)?;
285                    let field_name: String = read_wasm_name(sec_slice, &mut scale_factor)?;
286                    let kind: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
287                        WasmDynamicError::InvalidWasmBinary("truncated import kind".to_string())
288                    })?;
289                    scale_factor += 1;
290                    if kind == 0x00 {
291                        let type_idx: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
292                        module
293                            .get_mut_imports()
294                            .push(WasmImportEntry::new(mod_name, field_name, type_idx));
295                    } else {
296                        return Err(WasmDynamicError::InvalidWasmBinary(
297                            "unsupported non-function import kind".to_string(),
298                        ));
299                    }
300                }
301            }
302            WASM_SEC_FUNCTION => {
303                let count: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
304                for _ in 0..count {
305                    func_type_indices.push(read_uleb128(sec_slice, &mut scale_factor)?);
306                }
307            }
308            WASM_SEC_MEMORY => {
309                let count: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
310                if count > 0 {
311                    let flags: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
312                        WasmDynamicError::InvalidWasmBinary("truncated memory limits".to_string())
313                    })?;
314                    scale_factor += 1;
315                    let min_pages: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
316                    if (flags & 0x01) != 0 {
317                        let _: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
318                    }
319                    let req_bytes: usize = (min_pages as usize).saturating_mul(WASM_PAGE_BYTES);
320                    if req_bytes > config.get_max_memory_bytes() {
321                        return Err(WasmDynamicError::MemoryLimitExceeded {
322                            requested: req_bytes,
323                            limit: config.get_max_memory_bytes(),
324                        });
325                    }
326                    module.set_memory_min_pages(min_pages.max(1));
327                }
328            }
329            WASM_SEC_GLOBAL => {
330                let count: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
331                for _ in 0..count {
332                    let val_type: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
333                        WasmDynamicError::InvalidWasmBinary(WASM_ERR_GLOBAL_SECTION.to_string())
334                    })?;
335                    scale_factor += 1;
336                    let mut_flag: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
337                        WasmDynamicError::InvalidWasmBinary(WASM_ERR_GLOBAL_SECTION.to_string())
338                    })?;
339                    scale_factor += 1;
340                    let init_op: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
341                        WasmDynamicError::InvalidWasmBinary(WASM_ERR_GLOBAL_SECTION.to_string())
342                    })?;
343                    scale_factor += 1;
344                    let init_val: i32 = if init_op == OP_I32_CONST {
345                        read_sleb128(sec_slice, &mut scale_factor)?
346                    } else {
347                        return Err(WasmDynamicError::InvalidWasmBinary(
348                            WASM_ERR_GLOBAL_SECTION.to_string(),
349                        ));
350                    };
351                    let end_op: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
352                        WasmDynamicError::InvalidWasmBinary(WASM_ERR_GLOBAL_SECTION.to_string())
353                    })?;
354                    scale_factor += 1;
355                    if end_op != OP_END {
356                        return Err(WasmDynamicError::InvalidWasmBinary(
357                            WASM_ERR_GLOBAL_SECTION.to_string(),
358                        ));
359                    }
360                    module.get_mut_globals().push(WasmGlobalEntry::new(
361                        val_type,
362                        mut_flag != 0,
363                        init_val,
364                    ));
365                }
366            }
367            WASM_SEC_EXPORT => {
368                let count: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
369                for _ in 0..count {
370                    let exp_name: String = read_wasm_name(sec_slice, &mut scale_factor)?;
371                    let kind: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
372                        WasmDynamicError::InvalidWasmBinary("truncated export kind".to_string())
373                    })?;
374                    scale_factor += 1;
375                    let idx: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
376                    if kind == 0x00 {
377                        let _: Option<u32> = module.get_mut_exports().insert(exp_name, idx);
378                    }
379                }
380            }
381            WASM_SEC_CODE => {
382                let count: usize = read_uleb128(sec_slice, &mut scale_factor)? as usize;
383                if count != func_type_indices.len() {
384                    return Err(WasmDynamicError::InvalidWasmBinary(
385                        "function/code count mismatch".to_string(),
386                    ));
387                }
388                for type_idx in func_type_indices.iter().copied() {
389                    let body_len: usize = read_uleb128(sec_slice, &mut scale_factor)? as usize;
390                    let body_end: usize = scale_factor.saturating_add(body_len);
391                    if body_end > sec_slice.len() {
392                        return Err(WasmDynamicError::InvalidWasmBinary(
393                            "truncated code body".to_string(),
394                        ));
395                    }
396                    let local_decl_groups: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
397                    let mut extra_locals: usize = 0;
398                    for _ in 0..local_decl_groups {
399                        let lcount: usize = read_uleb128(sec_slice, &mut scale_factor)? as usize;
400                        scale_factor = scale_factor.saturating_add(1);
401                        extra_locals = extra_locals.saturating_add(lcount);
402                    }
403                    if scale_factor > body_end {
404                        return Err(WasmDynamicError::InvalidWasmBinary(
405                            "invalid local declarations".to_string(),
406                        ));
407                    }
408                    let code: Vec<u8> = sec_slice[scale_factor..body_end].to_vec();
409                    let is_pure_no_mem: bool = wasm_body_is_pure_no_memory(code.as_slice());
410                    scale_factor = body_end;
411                    let mut parsed_fn: WasmParsedFunction =
412                        WasmParsedFunction::new(type_idx, extra_locals, code);
413                    parsed_fn.set_pure_no_memory(is_pure_no_mem);
414                    module.get_mut_functions().push(parsed_fn);
415                }
416            }
417            WASM_SEC_DATA => {
418                let count: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
419                for _ in 0..count {
420                    let flags: u32 = read_uleb128(sec_slice, &mut scale_factor)?;
421                    if flags == 1 {
422                        let data_len: usize = read_uleb128(sec_slice, &mut scale_factor)? as usize;
423                        let data_end: usize = scale_factor.saturating_add(data_len);
424                        if data_end > sec_slice.len() {
425                            return Err(WasmDynamicError::InvalidWasmBinary(
426                                "truncated data segment bytes".to_string(),
427                            ));
428                        }
429                        scale_factor = data_end;
430                        continue;
431                    }
432                    if flags != 0 {
433                        return Err(WasmDynamicError::InvalidWasmBinary(
434                            "unsupported passive data segment".to_string(),
435                        ));
436                    }
437                    let op: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
438                        WasmDynamicError::InvalidWasmBinary("truncated data offset".to_string())
439                    })?;
440                    scale_factor += 1;
441                    if op != OP_I32_CONST {
442                        return Err(WasmDynamicError::InvalidWasmBinary(
443                            "expected i32.const in data offset".to_string(),
444                        ));
445                    }
446                    let offset: u32 = read_sleb128(sec_slice, &mut scale_factor)?.max(0) as u32;
447                    let end_op: u8 = *sec_slice.get(scale_factor).ok_or_else(|| {
448                        WasmDynamicError::InvalidWasmBinary(
449                            "missing end in data offset".to_string(),
450                        )
451                    })?;
452                    scale_factor += 1;
453                    if end_op != OP_END {
454                        return Err(WasmDynamicError::InvalidWasmBinary(
455                            "malformed data offset expr".to_string(),
456                        ));
457                    }
458                    let data_len: usize = read_uleb128(sec_slice, &mut scale_factor)? as usize;
459                    let data_end: usize = scale_factor.saturating_add(data_len);
460                    if data_end > sec_slice.len() {
461                        return Err(WasmDynamicError::InvalidWasmBinary(
462                            "truncated data segment bytes".to_string(),
463                        ));
464                    }
465                    let seg_bytes: Vec<u8> = sec_slice[scale_factor..data_end].to_vec();
466                    scale_factor = data_end;
467                    module
468                        .get_mut_data_segments()
469                        .push(WasmDataSegment::new(offset, seg_bytes));
470                }
471            }
472            WASM_SEC_TABLE | WASM_SEC_ELEMENT | WASM_SEC_DATA_COUNT => {}
473            _ => {}
474        }
475    }
476    if module.get_memory_min_pages() == 0 {
477        module.set_memory_min_pages(1);
478    }
479    Ok(module)
480}
481
482/// Reads a bounded UTF-8 slice from WASM linear memory, returning `MemoryOutOfBounds` on invalid ranges.
483///
484/// # Arguments
485///
486/// - `&[u8]` - Active linear memory buffer.
487/// - `u32` - Start pointer offset.
488/// - `u32` - Byte length to read.
489///
490/// # Returns
491///
492/// - `Result<&str, WasmDynamicError>` - Validated UTF-8 slice or memory error.
493fn read_memory_str(memory: &[u8], ptr: u32, len: u32) -> Result<&str, WasmDynamicError> {
494    let start: usize = ptr as usize;
495    let end: usize = start.saturating_add(len as usize);
496    if end > memory.len() {
497        return Err(WasmDynamicError::MemoryOutOfBounds {
498            addr: ptr,
499            len,
500            memory_size: memory.len(),
501        });
502    }
503    from_utf8(&memory[start..end])
504        .map_err(|_| WasmDynamicError::InvalidUiPayload("non-UTF8 memory buffer".to_string()))
505}
506
507/// Statically inspects a WebAssembly function bytecode body and returns `true` when it touches zero linear memory and performs zero calls.
508///
509/// # Arguments
510///
511/// - `&[u8]` - Raw bytecode instruction slice for one defined function.
512///
513/// # Returns
514///
515/// - `bool` - `true` when linear memory allocation and data segment copying may be skipped safely.
516#[must_use]
517fn wasm_body_is_pure_no_memory(code: &[u8]) -> bool {
518    const MEMORY_OR_CALL_OPS: [u8; 3] = [OP_CALL, OP_I32_LOAD, OP_I32_STORE];
519    const BLOCK_OPS: [u8; 3] = [OP_BLOCK, OP_LOOP, OP_IF];
520    const ULEB_IMM_OPS: [u8; 4] = [OP_LOCAL_GET, OP_LOCAL_SET, OP_BR, OP_BR_IF];
521    const ZERO_IMM_OPS: [u8; 15] = [
522        OP_UNREACHABLE,
523        OP_NOP,
524        OP_ELSE,
525        OP_END,
526        OP_RETURN,
527        OP_DROP,
528        OP_I32_EQZ,
529        OP_I32_EQ,
530        OP_I32_NE,
531        OP_I32_LT_S,
532        OP_I32_GT_S,
533        OP_I32_ADD,
534        OP_I32_SUB,
535        OP_I32_MUL,
536        OP_I32_DIV_S,
537    ];
538    let mut pc: usize = 0;
539    while pc < code.len() {
540        let op: u8 = code[pc];
541        pc += 1;
542        if MEMORY_OR_CALL_OPS.contains(&op) {
543            return false;
544        }
545        if BLOCK_OPS.contains(&op) {
546            if pc >= code.len() {
547                return false;
548            }
549            pc += 1;
550        } else if op == OP_I32_CONST {
551            if read_sleb128(code, &mut pc).is_err() {
552                return false;
553            }
554        } else if ULEB_IMM_OPS.contains(&op) {
555            if read_uleb128(code, &mut pc).is_err() {
556                return false;
557            }
558        } else if !ZERO_IMM_OPS.contains(&op) {
559            return false;
560        }
561    }
562    true
563}
564
565/// Advances `pc` past any immediate operands belonging to `op` when scanning skipped control-flow blocks.
566///
567/// # Arguments
568///
569/// - `&[u8]` - Raw function bytecode slice.
570/// - `u8` - Opcode byte just consumed at `pc - 1`.
571/// - `&mut usize` - Mutable bytecode cursor positioned immediately after `op`.
572///
573/// # Returns
574///
575/// - `Result<(), WasmDynamicError>` - `Ok(())` when immediates were skipped cleanly.
576fn skip_wasm_op_immediates(code: &[u8], op: u8, pc: &mut usize) -> Result<(), WasmDynamicError> {
577    if op == OP_I32_CONST {
578        let _: i32 = read_sleb128(code, pc)?;
579    } else if op == OP_LOCAL_GET
580        || op == OP_LOCAL_SET
581        || op == OP_LOCAL_TEE
582        || op == OP_GLOBAL_GET
583        || op == OP_GLOBAL_SET
584        || op == OP_CALL
585        || op == OP_BR
586        || op == OP_BR_IF
587        || op == OP_MEMORY_SIZE
588        || op == OP_MEMORY_GROW
589    {
590        let _: u32 = read_uleb128(code, pc)?;
591    } else if op == OP_I32_LOAD
592        || op == OP_I32_LOAD8_S
593        || op == OP_I32_LOAD8_U
594        || op == OP_I32_LOAD16_S
595        || op == OP_I32_LOAD16_U
596        || op == OP_I32_STORE
597        || op == OP_I32_STORE8
598        || op == OP_I32_STORE16
599    {
600        let _: u32 = read_uleb128(code, pc)?;
601        let _: u32 = read_uleb128(code, pc)?;
602    } else if op == OP_BR_TABLE {
603        let count: u32 = read_uleb128(code, pc)?;
604        for _ in 0..=count {
605            let _: u32 = read_uleb128(code, pc)?;
606        }
607    } else if op == OP_PREFIX_MISC {
608        let sub_op: u32 = read_uleb128(code, pc)?;
609        if sub_op == MISC_MEMORY_COPY {
610            let _: u32 = read_uleb128(code, pc)?;
611            let _: u32 = read_uleb128(code, pc)?;
612        } else if sub_op == MISC_MEMORY_FILL {
613            let _: u32 = read_uleb128(code, pc)?;
614        }
615    }
616    Ok(())
617}
618
619/// Executes a single WASM export against an explicit zeroed linear memory buffer and reports the high-water dirty byte offset.
620///
621/// # Arguments
622///
623/// - `&WasmParsedModule` - Validated `.wasm` module.
624/// - `u32` - Absolute function index resolved from exports.
625/// - `&[i32]` - Positional `i32` arguments.
626/// - `&WasmSandboxConfig` - Fuel and memory limits.
627/// - `&mut Vec<u8>` - Pre-zeroed linear memory backing buffer sized to at least `initial_mem_bytes`.
628/// - `usize` - Initial active linear memory byte length.
629///
630/// # Returns
631///
632/// - `(Result<WasmExecutionOutput, WasmDynamicError>, usize)` - Execution result paired with the dirty prefix length to re-zero.
633fn execute_wasm_with_memory_slice(
634    module: &WasmParsedModule,
635    func_idx: u32,
636    args: &[i32],
637    config: &WasmSandboxConfig,
638    memory: &mut Vec<u8>,
639    initial_mem_bytes: usize,
640) -> (Result<WasmExecutionOutput, WasmDynamicError>, usize) {
641    let mut dirty_end: usize = 0;
642    for seg in module.get_data_segments().iter() {
643        let start: usize = seg.get_offset() as usize;
644        let end: usize = start.saturating_add(seg.get_bytes().len());
645        if end > initial_mem_bytes {
646            return (
647                Err(WasmDynamicError::MemoryOutOfBounds {
648                    addr: seg.get_offset(),
649                    len: seg.get_bytes().len() as u32,
650                    memory_size: initial_mem_bytes,
651                }),
652                dirty_end,
653            );
654        }
655        memory[start..end].copy_from_slice(seg.get_bytes().as_slice());
656        if end > dirty_end {
657            dirty_end = end;
658        }
659    }
660    let global_count: usize = module.get_globals().len();
661    let mut inline_globals: [i32; 8] = [0; 8];
662    let mut spill_globals: Vec<i32> = if global_count > inline_globals.len() {
663        module
664            .get_globals()
665            .iter()
666            .map(WasmGlobalEntry::get_init_i32)
667            .collect()
668    } else {
669        for (idx, entry) in module.get_globals().iter().enumerate() {
670            inline_globals[idx] = entry.get_init_i32();
671        }
672        Vec::new()
673    };
674    let globals_slice: &mut [i32] = if spill_globals.is_empty() {
675        &mut inline_globals[..global_count]
676    } else {
677        spill_globals.as_mut_slice()
678    };
679    let mut out: WasmExecutionOutput = WasmExecutionOutput::default();
680    let mut exec: WasmExecContext<'_> = WasmExecContext {
681        memory,
682        memory_len: initial_mem_bytes,
683        memory_max_bytes: config.get_max_memory_bytes(),
684        globals: globals_slice,
685        out: &mut out,
686        fuel_used: 0,
687        max_fuel: config.get_max_fuel(),
688        depth: 0,
689        dirty_end,
690    };
691    let ret_res: Result<i32, WasmDynamicError> =
692        execute_wasm_func_index(module, func_idx, args, &mut exec);
693    let final_dirty: usize = exec.dirty_end;
694    let fuel_used: u64 = exec.fuel_used;
695    match ret_res {
696        Ok(ret) => {
697            out.set_return_value(ret);
698            out.set_fuel_used(fuel_used);
699            (Ok(out), final_dirty)
700        }
701        Err(err) => (Err(err), final_dirty),
702    }
703}
704
705/// Executes an exported WebAssembly function inside a fuel-metered, memory-bounded sandbox.
706///
707/// # Arguments
708///
709/// - `&WasmParsedModule` - Validated `.wasm` module.
710/// - `&str` - Exported function name (e.g. `"euv_render"`, `"euv_on_event"`, `"euv_abi_version"`).
711/// - `&[i32]` - Positional `i32` arguments passed to the export.
712/// - `&WasmSandboxConfig` - Fuel and memory limits.
713///
714/// # Returns
715///
716/// - `Result<WasmExecutionOutput, WasmDynamicError>` - Execution output including emitted native UI spec or bundle.
717pub fn execute_wasm_export(
718    module: &WasmParsedModule,
719    export_name: &str,
720    args: &[i32],
721    config: &WasmSandboxConfig,
722) -> Result<WasmExecutionOutput, WasmDynamicError> {
723    let func_idx: u32 = *module
724        .get_exports()
725        .get(export_name)
726        .ok_or_else(|| WasmDynamicError::MissingExport(export_name.to_string()))?;
727    let mem_bytes: usize =
728        (module.get_memory_min_pages().max(1) as usize).saturating_mul(WASM_PAGE_BYTES);
729    if mem_bytes > config.get_max_memory_bytes() {
730        return Err(WasmDynamicError::MemoryLimitExceeded {
731            requested: mem_bytes,
732            limit: config.get_max_memory_bytes(),
733        });
734    }
735    let import_count: usize = module.get_imports().len();
736    let is_pure_no_memory: bool = (func_idx as usize) >= import_count
737        && module
738            .get_functions()
739            .get((func_idx as usize) - import_count)
740            .is_some_and(WasmParsedFunction::get_pure_no_memory);
741    if is_pure_no_memory {
742        for seg in module.get_data_segments().iter() {
743            let start: usize = seg.get_offset() as usize;
744            let end: usize = start.saturating_add(seg.get_bytes().len());
745            if end > mem_bytes {
746                return Err(WasmDynamicError::MemoryOutOfBounds {
747                    addr: seg.get_offset(),
748                    len: seg.get_bytes().len() as u32,
749                    memory_size: mem_bytes,
750                });
751            }
752        }
753        let mut out: WasmExecutionOutput = WasmExecutionOutput::default();
754        let mut empty_mem: Vec<u8> = Vec::new();
755        let mut empty_globals: [i32; 0] = [];
756        let mut exec: WasmExecContext<'_> = WasmExecContext {
757            memory: &mut empty_mem,
758            memory_len: 0,
759            memory_max_bytes: config.get_max_memory_bytes(),
760            globals: &mut empty_globals,
761            out: &mut out,
762            fuel_used: 0,
763            max_fuel: config.get_max_fuel(),
764            depth: 0,
765            dirty_end: 0,
766        };
767        let ret: i32 = execute_wasm_func_index(module, func_idx, args, &mut exec)?;
768        let fuel_used: u64 = exec.fuel_used;
769        out.set_return_value(ret);
770        out.set_fuel_used(fuel_used);
771        return Ok(out);
772    }
773    WASM_LINEAR_MEMORY_POOL.with(|cell: &RefCell<WasmMemoryPool>| {
774        if let Ok(mut pool) = cell.try_borrow_mut() {
775            if pool.buffer.len() < mem_bytes {
776                pool.buffer.resize(mem_bytes, 0);
777            }
778            let (res, dirty_end): (Result<WasmExecutionOutput, WasmDynamicError>, usize) =
779                execute_wasm_with_memory_slice(
780                    module,
781                    func_idx,
782                    args,
783                    config,
784                    &mut pool.buffer,
785                    mem_bytes,
786                );
787            let clear_len: usize = dirty_end.min(pool.buffer.len());
788            if clear_len > 0 {
789                pool.buffer[..clear_len].fill(0);
790            }
791            let max_retained_bytes: usize = WASM_PAGE_BYTES.saturating_mul(4);
792            if pool.buffer.len() > max_retained_bytes {
793                pool.buffer.truncate(max_retained_bytes);
794                pool.buffer.shrink_to_fit();
795            }
796            res
797        } else {
798            let mut local_mem: Vec<u8> = vec![0; mem_bytes];
799            let (res, _): (Result<WasmExecutionOutput, WasmDynamicError>, usize) =
800                execute_wasm_with_memory_slice(
801                    module,
802                    func_idx,
803                    args,
804                    config,
805                    &mut local_mem,
806                    mem_bytes,
807                );
808            res
809        }
810    })
811}
812
813/// Evaluates an `i32` binary WebAssembly opcode if `op` matches one.
814///
815/// # Arguments
816///
817/// - `u8` - Bytecode opcode.
818/// - `&mut Vec<i32>` - Active operand stack.
819///
820/// # Returns
821///
822/// - `Result<Option<i32>, WasmDynamicError>` - Computed result if `op` is a supported binop, `None` otherwise.
823fn eval_i32_binop(op: u8, stack: &mut Vec<i32>) -> Result<Option<i32>, WasmDynamicError> {
824    let is_binop: bool = matches!(
825        op,
826        OP_I32_EQ
827            | OP_I32_NE
828            | OP_I32_LT_S
829            | OP_I32_LT_U
830            | OP_I32_GT_S
831            | OP_I32_GT_U
832            | OP_I32_LE_S
833            | OP_I32_LE_U
834            | OP_I32_GE_S
835            | OP_I32_GE_U
836            | OP_I32_ADD
837            | OP_I32_SUB
838            | OP_I32_MUL
839            | OP_I32_DIV_S
840            | OP_I32_DIV_U
841            | OP_I32_REM_S
842            | OP_I32_REM_U
843            | OP_I32_AND
844            | OP_I32_OR
845            | OP_I32_XOR
846            | OP_I32_SHL
847            | OP_I32_SHR_S
848            | OP_I32_SHR_U
849            | OP_I32_ROTL
850            | OP_I32_ROTR
851    );
852    if !is_binop {
853        return Ok(None);
854    }
855    let blue_val: i32 = stack
856        .pop()
857        .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
858    let alpha_val: i32 = stack
859        .pop()
860        .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
861    let res: i32 = match op {
862        OP_I32_EQ => i32::from(alpha_val == blue_val),
863        OP_I32_NE => i32::from(alpha_val != blue_val),
864        OP_I32_LT_S => i32::from(alpha_val < blue_val),
865        OP_I32_LT_U => i32::from((alpha_val as u32) < (blue_val as u32)),
866        OP_I32_GT_S => i32::from(alpha_val > blue_val),
867        OP_I32_GT_U => i32::from((alpha_val as u32) > (blue_val as u32)),
868        OP_I32_LE_S => i32::from(alpha_val <= blue_val),
869        OP_I32_LE_U => i32::from((alpha_val as u32) <= (blue_val as u32)),
870        OP_I32_GE_S => i32::from(alpha_val >= blue_val),
871        OP_I32_GE_U => i32::from((alpha_val as u32) >= (blue_val as u32)),
872        OP_I32_ADD => alpha_val.wrapping_add(blue_val),
873        OP_I32_SUB => alpha_val.wrapping_sub(blue_val),
874        OP_I32_MUL => alpha_val.wrapping_mul(blue_val),
875        OP_I32_DIV_S => {
876            if blue_val == 0 {
877                return Err(WasmDynamicError::ExecutionTrap(
878                    WASM_ERR_DIV_BY_ZERO.to_string(),
879                ));
880            }
881            if alpha_val == i32::MIN && blue_val == -1 {
882                return Err(WasmDynamicError::ExecutionTrap(
883                    WASM_ERR_DIV_OVERFLOW.to_string(),
884                ));
885            }
886            alpha_val.wrapping_div(blue_val)
887        }
888        OP_I32_DIV_U => {
889            if blue_val == 0 {
890                return Err(WasmDynamicError::ExecutionTrap(
891                    WASM_ERR_DIV_BY_ZERO.to_string(),
892                ));
893            }
894            ((alpha_val as u32) / (blue_val as u32)) as i32
895        }
896        OP_I32_REM_S => {
897            if blue_val == 0 {
898                return Err(WasmDynamicError::ExecutionTrap(
899                    WASM_ERR_DIV_BY_ZERO.to_string(),
900                ));
901            }
902            alpha_val.wrapping_rem(blue_val)
903        }
904        OP_I32_REM_U => {
905            if blue_val == 0 {
906                return Err(WasmDynamicError::ExecutionTrap(
907                    WASM_ERR_DIV_BY_ZERO.to_string(),
908                ));
909            }
910            ((alpha_val as u32) % (blue_val as u32)) as i32
911        }
912        OP_I32_AND => alpha_val & blue_val,
913        OP_I32_OR => alpha_val | blue_val,
914        OP_I32_XOR => alpha_val ^ blue_val,
915        OP_I32_SHL => alpha_val.wrapping_shl(blue_val as u32),
916        OP_I32_SHR_S => alpha_val.wrapping_shr(blue_val as u32),
917        OP_I32_SHR_U => ((alpha_val as u32).wrapping_shr(blue_val as u32)) as i32,
918        OP_I32_ROTL => (alpha_val as u32).rotate_left((blue_val as u32) & 31) as i32,
919        OP_I32_ROTR => (alpha_val as u32).rotate_right((blue_val as u32) & 31) as i32,
920        _ => 0,
921    };
922    Ok(Some(res))
923}
924
925/// Internal recursive bytecode interpreter executing a single WASM function or host import call.
926///
927/// # Arguments
928///
929/// - `&WasmParsedModule` - Active parsed module.
930/// - `u32` - Absolute function index (imports first, then defined functions).
931/// - `&[i32]` - Call arguments.
932/// - `&mut WasmExecContext<'_>` - Shared mutable memory, host output, fuel, and depth state.
933///
934/// # Returns
935///
936/// - `Result<i32, WasmDynamicError>` - Return value or sandbox error.
937fn execute_wasm_func_index(
938    module: &WasmParsedModule,
939    func_idx: u32,
940    args: &[i32],
941    exec: &mut WasmExecContext<'_>,
942) -> Result<i32, WasmDynamicError> {
943    if exec.depth > 32 {
944        return Err(WasmDynamicError::ExecutionTrap(
945            "call stack depth overflow".to_string(),
946        ));
947    }
948    let import_count: usize = module.get_imports().len();
949    if (func_idx as usize) < import_count {
950        let imp: &WasmImportEntry = &module.get_imports()[func_idx as usize];
951        let ptr: u32 = args.first().copied().unwrap_or(0).max(0) as u32;
952        let len: u32 = args.get(1).copied().unwrap_or(0).max(0) as u32;
953        let text: &str = read_memory_str(&exec.memory[..exec.memory_len], ptr, len)?;
954        if imp.get_name() == WASM_IMPORT_EMIT_UI {
955            let spec: DynamicNodeSpec =
956                from_str::<DynamicNodeSpec>(text).map_err(|err: serde_json::Error| {
957                    WasmDynamicError::InvalidUiPayload(err.to_string())
958                })?;
959            exec.out.set_emitted_spec(Some(spec));
960            return Ok(1);
961        }
962        if imp.get_name() == WASM_IMPORT_EMIT_BUNDLE {
963            let bundle: DynamicUpdateBundle =
964                from_str::<DynamicUpdateBundle>(text).map_err(|err: serde_json::Error| {
965                    WasmDynamicError::InvalidUiPayload(err.to_string())
966                })?;
967            exec.out.set_emitted_bundle(Some(bundle));
968            return Ok(1);
969        }
970        if imp.get_name() == WASM_IMPORT_LOG {
971            exec.out.get_mut_logs().push(text.to_string());
972            return Ok(1);
973        }
974        return Err(WasmDynamicError::ExecutionTrap(format!(
975            "unknown host import {}::{}",
976            imp.get_module(),
977            imp.get_name()
978        )));
979    }
980    let local_idx: usize = (func_idx as usize) - import_count;
981    let func: &WasmParsedFunction = module
982        .get_functions()
983        .get(local_idx)
984        .ok_or_else(|| WasmDynamicError::ExecutionTrap("invalid function index".to_string()))?;
985    let sig: WasmFuncSignature = module
986        .get_types()
987        .get(func.get_type_index() as usize)
988        .copied()
989        .unwrap_or_default();
990    let total_locals: usize = sig
991        .get_param_count()
992        .saturating_add(func.get_extra_locals())
993        .max(args.len());
994    let mut inline_locals: [i32; 16] = [0; 16];
995    let mut spill_locals: Vec<i32> = if total_locals > inline_locals.len() {
996        vec![0; total_locals]
997    } else {
998        Vec::new()
999    };
1000    let locals: &mut [i32] = if spill_locals.is_empty() {
1001        &mut inline_locals[..total_locals]
1002    } else {
1003        spill_locals.as_mut_slice()
1004    };
1005    for (idx, val) in args.iter().copied().enumerate() {
1006        if idx < locals.len() {
1007            locals[idx] = val;
1008        }
1009    }
1010    let code: &[u8] = func.get_body().as_slice();
1011    let mut stack: Vec<i32> = Vec::with_capacity(32);
1012    let mut labels: Vec<(u8, usize)> = Vec::with_capacity(16);
1013    let mut pc: usize = 0;
1014    while pc < code.len() {
1015        exec.fuel_used = exec.fuel_used.saturating_add(1);
1016        if exec.fuel_used > exec.max_fuel {
1017            return Err(WasmDynamicError::OutOfFuel {
1018                limit: exec.max_fuel,
1019            });
1020        }
1021        let op: u8 = code[pc];
1022        pc += 1;
1023        match op {
1024            OP_UNREACHABLE => {
1025                return Err(WasmDynamicError::ExecutionTrap(
1026                    "wasm unreachable instruction trapped".to_string(),
1027                ));
1028            }
1029            OP_NOP => {}
1030            OP_BLOCK | OP_LOOP => {
1031                let _: u8 = *code.get(pc).unwrap_or(&0x40);
1032                pc = pc.saturating_add(1);
1033                labels.push((op, pc));
1034            }
1035            OP_IF => {
1036                let _: u8 = *code.get(pc).unwrap_or(&0x40);
1037                pc = pc.saturating_add(1);
1038                let cond: i32 = stack.pop().ok_or_else(|| {
1039                    WasmDynamicError::ExecutionTrap("stack underflow on if".to_string())
1040                })?;
1041                if cond != 0 {
1042                    labels.push((OP_IF, pc));
1043                } else {
1044                    let mut nesting: usize = 0;
1045                    while pc < code.len() {
1046                        let scan: u8 = code[pc];
1047                        pc += 1;
1048                        if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
1049                            nesting += 1;
1050                            pc = pc.saturating_add(1);
1051                        } else if scan == OP_ELSE && nesting == 0 {
1052                            labels.push((OP_ELSE, pc));
1053                            break;
1054                        } else if scan == OP_END {
1055                            if nesting == 0 {
1056                                break;
1057                            }
1058                            nesting -= 1;
1059                        } else {
1060                            skip_wasm_op_immediates(code, scan, &mut pc)?;
1061                        }
1062                    }
1063                }
1064            }
1065            OP_ELSE => {
1066                let _: Option<(u8, usize)> = labels.pop();
1067                let mut nesting: usize = 0;
1068                while pc < code.len() {
1069                    let scan: u8 = code[pc];
1070                    pc += 1;
1071                    if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
1072                        nesting += 1;
1073                        pc = pc.saturating_add(1);
1074                    } else if scan == OP_END {
1075                        if nesting == 0 {
1076                            break;
1077                        }
1078                        nesting -= 1;
1079                    } else {
1080                        skip_wasm_op_immediates(code, scan, &mut pc)?;
1081                    }
1082                }
1083            }
1084            OP_END => {
1085                if labels.pop().is_none() {
1086                    break;
1087                }
1088            }
1089            OP_BR | OP_BR_IF | OP_BR_TABLE => {
1090                let (take_branch, target_depth): (bool, usize) = if op == OP_BR_TABLE {
1091                    let count: usize = read_uleb128(code, &mut pc)? as usize;
1092                    let mut targets: Vec<usize> = Vec::with_capacity(count);
1093                    for _ in 0..count {
1094                        targets.push(read_uleb128(code, &mut pc)? as usize);
1095                    }
1096                    let default_target: usize = read_uleb128(code, &mut pc)? as usize;
1097                    let idx: usize = stack.pop().unwrap_or(0) as u32 as usize;
1098                    let chosen: usize = targets.get(idx).copied().unwrap_or(default_target);
1099                    (true, chosen)
1100                } else {
1101                    let depth_val: usize = read_uleb128(code, &mut pc)? as usize;
1102                    let taken: bool = if op == OP_BR_IF {
1103                        stack.pop().unwrap_or(0) != 0
1104                    } else {
1105                        true
1106                    };
1107                    (taken, depth_val)
1108                };
1109                if take_branch {
1110                    if target_depth >= labels.len() {
1111                        break;
1112                    }
1113                    let keep_len: usize = labels.len() - target_depth;
1114                    let (lbl_op, lbl_pc): (u8, usize) = labels[keep_len - 1];
1115                    if lbl_op == OP_LOOP {
1116                        labels.truncate(keep_len);
1117                        pc = lbl_pc;
1118                    } else {
1119                        labels.truncate(keep_len - 1);
1120                        let mut nesting: usize = 0;
1121                        while pc < code.len() {
1122                            let scan: u8 = code[pc];
1123                            pc += 1;
1124                            if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
1125                                nesting += 1;
1126                                pc = pc.saturating_add(1);
1127                            } else if scan == OP_END {
1128                                if nesting == 0 {
1129                                    break;
1130                                }
1131                                nesting -= 1;
1132                            } else {
1133                                skip_wasm_op_immediates(code, scan, &mut pc)?;
1134                            }
1135                        }
1136                    }
1137                }
1138            }
1139            OP_RETURN => break,
1140            OP_CALL => {
1141                let callee: u32 = read_uleb128(code, &mut pc)?;
1142                let callee_type: u32 = if (callee as usize) < import_count {
1143                    module.get_imports()[callee as usize].get_type_index()
1144                } else {
1145                    module
1146                        .get_functions()
1147                        .get((callee as usize) - import_count)
1148                        .map(WasmParsedFunction::get_type_index)
1149                        .unwrap_or(0)
1150                };
1151                let csig: WasmFuncSignature = module
1152                    .get_types()
1153                    .get(callee_type as usize)
1154                    .copied()
1155                    .unwrap_or_default();
1156                let param_count: usize = csig.get_param_count();
1157                let mut inline_args: [i32; 8] = [0; 8];
1158                let mut spill_args: Vec<i32> = if param_count > inline_args.len() {
1159                    vec![0; param_count]
1160                } else {
1161                    Vec::new()
1162                };
1163                let call_args: &mut [i32] = if spill_args.is_empty() {
1164                    &mut inline_args[..param_count]
1165                } else {
1166                    spill_args.as_mut_slice()
1167                };
1168                for idx in (0..param_count).rev() {
1169                    call_args[idx] = stack.pop().ok_or_else(|| {
1170                        WasmDynamicError::ExecutionTrap("stack underflow on call".to_string())
1171                    })?;
1172                }
1173                exec.depth = exec.depth.saturating_add(1);
1174                let call_res: Result<i32, WasmDynamicError> =
1175                    execute_wasm_func_index(module, callee, call_args, exec);
1176                exec.depth = exec.depth.saturating_sub(1);
1177                let call_ret: i32 = call_res?;
1178                if csig.get_result_count() > 0 {
1179                    stack.push(call_ret);
1180                }
1181            }
1182            OP_DROP => {
1183                let _: Option<i32> = stack.pop();
1184            }
1185            OP_SELECT => {
1186                let cond: i32 = stack.pop().ok_or_else(|| {
1187                    WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_SELECT.to_string())
1188                })?;
1189                let val_false: i32 = stack.pop().ok_or_else(|| {
1190                    WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_SELECT.to_string())
1191                })?;
1192                let val_true: i32 = stack.pop().ok_or_else(|| {
1193                    WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_SELECT.to_string())
1194                })?;
1195                stack.push(if cond != 0 { val_true } else { val_false });
1196            }
1197            OP_LOCAL_GET => {
1198                let idx: usize = read_uleb128(code, &mut pc)? as usize;
1199                let val: i32 = *locals.get(idx).unwrap_or(&0);
1200                stack.push(val);
1201            }
1202            OP_LOCAL_SET => {
1203                let idx: usize = read_uleb128(code, &mut pc)? as usize;
1204                let val: i32 = stack.pop().ok_or_else(|| {
1205                    WasmDynamicError::ExecutionTrap("stack underflow on local.set".to_string())
1206                })?;
1207                if idx < locals.len() {
1208                    locals[idx] = val;
1209                }
1210            }
1211            OP_LOCAL_TEE => {
1212                let idx: usize = read_uleb128(code, &mut pc)? as usize;
1213                let val: i32 = *stack.last().ok_or_else(|| {
1214                    WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_LOCAL_TEE.to_string())
1215                })?;
1216                if idx < locals.len() {
1217                    locals[idx] = val;
1218                }
1219            }
1220            OP_GLOBAL_GET => {
1221                let idx: usize = read_uleb128(code, &mut pc)? as usize;
1222                let val: i32 = *exec.globals.get(idx).ok_or_else(|| {
1223                    WasmDynamicError::ExecutionTrap(WASM_ERR_GLOBAL_INDEX.to_string())
1224                })?;
1225                stack.push(val);
1226            }
1227            OP_GLOBAL_SET => {
1228                let idx: usize = read_uleb128(code, &mut pc)? as usize;
1229                let val: i32 = stack.pop().ok_or_else(|| {
1230                    WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_GLOBAL_SET.to_string())
1231                })?;
1232                let is_mutable: bool = module
1233                    .get_globals()
1234                    .get(idx)
1235                    .map(WasmGlobalEntry::get_mutable)
1236                    .ok_or_else(|| {
1237                        WasmDynamicError::ExecutionTrap(WASM_ERR_GLOBAL_INDEX.to_string())
1238                    })?;
1239                if !is_mutable {
1240                    return Err(WasmDynamicError::ExecutionTrap(
1241                        WASM_ERR_IMMUTABLE_GLOBAL.to_string(),
1242                    ));
1243                }
1244                if let Some(slot) = exec.globals.get_mut(idx) {
1245                    *slot = val;
1246                }
1247            }
1248            OP_I32_LOAD | OP_I32_LOAD8_S | OP_I32_LOAD8_U | OP_I32_LOAD16_S | OP_I32_LOAD16_U => {
1249                let _: u32 = read_uleb128(code, &mut pc)?;
1250                let offset: u32 = read_uleb128(code, &mut pc)?;
1251                let base: u32 = stack.pop().unwrap_or(0) as u32;
1252                let width: usize = match op {
1253                    OP_I32_LOAD => 4,
1254                    OP_I32_LOAD16_S | OP_I32_LOAD16_U => 2,
1255                    _ => 1,
1256                };
1257                let addr: usize = (base as usize).saturating_add(offset as usize);
1258                if addr.saturating_add(width) > exec.memory_len {
1259                    return Err(WasmDynamicError::MemoryOutOfBounds {
1260                        addr: addr as u32,
1261                        len: width as u32,
1262                        memory_size: exec.memory_len,
1263                    });
1264                }
1265                let val: i32 = match op {
1266                    OP_I32_LOAD => i32::from_le_bytes([
1267                        exec.memory[addr],
1268                        exec.memory[addr + 1],
1269                        exec.memory[addr + 2],
1270                        exec.memory[addr + 3],
1271                    ]),
1272                    OP_I32_LOAD8_S => (exec.memory[addr] as i8) as i32,
1273                    OP_I32_LOAD8_U => exec.memory[addr] as i32,
1274                    OP_I32_LOAD16_S => {
1275                        i16::from_le_bytes([exec.memory[addr], exec.memory[addr + 1]]) as i32
1276                    }
1277                    OP_I32_LOAD16_U => {
1278                        u16::from_le_bytes([exec.memory[addr], exec.memory[addr + 1]]) as i32
1279                    }
1280                    _ => 0,
1281                };
1282                stack.push(val);
1283            }
1284            OP_I32_STORE | OP_I32_STORE8 | OP_I32_STORE16 => {
1285                let _: u32 = read_uleb128(code, &mut pc)?;
1286                let offset: u32 = read_uleb128(code, &mut pc)?;
1287                let val: i32 = stack.pop().unwrap_or(0);
1288                let base: u32 = stack.pop().unwrap_or(0) as u32;
1289                let width: usize = match op {
1290                    OP_I32_STORE => 4,
1291                    OP_I32_STORE16 => 2,
1292                    _ => 1,
1293                };
1294                let addr: usize = (base as usize).saturating_add(offset as usize);
1295                if addr.saturating_add(width) > exec.memory_len {
1296                    return Err(WasmDynamicError::MemoryOutOfBounds {
1297                        addr: addr as u32,
1298                        len: width as u32,
1299                        memory_size: exec.memory_len,
1300                    });
1301                }
1302                let write_end: usize = addr + width;
1303                match op {
1304                    OP_I32_STORE => {
1305                        exec.memory[addr..write_end].copy_from_slice(&val.to_le_bytes());
1306                    }
1307                    OP_I32_STORE16 => {
1308                        exec.memory[addr..write_end].copy_from_slice(&(val as u16).to_le_bytes());
1309                    }
1310                    _ => {
1311                        exec.memory[addr] = val as u8;
1312                    }
1313                }
1314                if write_end > exec.dirty_end {
1315                    exec.dirty_end = write_end;
1316                }
1317            }
1318            OP_MEMORY_SIZE => {
1319                let _: u32 = read_uleb128(code, &mut pc)?;
1320                stack.push((exec.memory_len / WASM_PAGE_BYTES) as i32);
1321            }
1322            OP_MEMORY_GROW => {
1323                let _: u32 = read_uleb128(code, &mut pc)?;
1324                let delta_pages: usize = stack.pop().unwrap_or(0).max(0) as usize;
1325                let old_pages: usize = exec.memory_len / WASM_PAGE_BYTES;
1326                let add_bytes: usize = delta_pages.saturating_mul(WASM_PAGE_BYTES);
1327                let next_len: usize = exec.memory_len.saturating_add(add_bytes);
1328                if next_len > exec.memory_max_bytes {
1329                    stack.push(-1);
1330                } else {
1331                    if exec.memory.len() < next_len {
1332                        exec.memory.resize(next_len, 0);
1333                    }
1334                    exec.memory_len = next_len;
1335                    stack.push(old_pages as i32);
1336                }
1337            }
1338            OP_PREFIX_MISC => {
1339                let sub_op: u32 = read_uleb128(code, &mut pc)?;
1340                if sub_op == MISC_MEMORY_COPY {
1341                    let _: u32 = read_uleb128(code, &mut pc)?;
1342                    let _: u32 = read_uleb128(code, &mut pc)?;
1343                    let len: usize = stack.pop().unwrap_or(0) as u32 as usize;
1344                    let src: usize = stack.pop().unwrap_or(0) as u32 as usize;
1345                    let dst: usize = stack.pop().unwrap_or(0) as u32 as usize;
1346                    if src.saturating_add(len) > exec.memory_len
1347                        || dst.saturating_add(len) > exec.memory_len
1348                    {
1349                        return Err(WasmDynamicError::MemoryOutOfBounds {
1350                            addr: dst.max(src) as u32,
1351                            len: len as u32,
1352                            memory_size: exec.memory_len,
1353                        });
1354                    }
1355                    exec.memory.copy_within(src..src + len, dst);
1356                    let write_end: usize = dst + len;
1357                    if write_end > exec.dirty_end {
1358                        exec.dirty_end = write_end;
1359                    }
1360                } else if sub_op == MISC_MEMORY_FILL {
1361                    let _: u32 = read_uleb128(code, &mut pc)?;
1362                    let len: usize = stack.pop().unwrap_or(0) as u32 as usize;
1363                    let byte_val: u8 = stack.pop().unwrap_or(0) as u8;
1364                    let dst: usize = stack.pop().unwrap_or(0) as u32 as usize;
1365                    if dst.saturating_add(len) > exec.memory_len {
1366                        return Err(WasmDynamicError::MemoryOutOfBounds {
1367                            addr: dst as u32,
1368                            len: len as u32,
1369                            memory_size: exec.memory_len,
1370                        });
1371                    }
1372                    let write_end: usize = dst + len;
1373                    exec.memory[dst..write_end].fill(byte_val);
1374                    if write_end > exec.dirty_end {
1375                        exec.dirty_end = write_end;
1376                    }
1377                } else {
1378                    return Err(WasmDynamicError::ExecutionTrap(format!(
1379                        "{WASM_ERR_UNSUPPORTED_MISC_OP}: 0x{sub_op:02x}"
1380                    )));
1381                }
1382            }
1383            OP_I32_CONST => {
1384                let val: i32 = read_sleb128(code, &mut pc)?;
1385                stack.push(val);
1386            }
1387            OP_I32_EQZ => {
1388                let alpha_val: i32 = stack.pop().unwrap_or(0);
1389                stack.push(if alpha_val == 0 { 1 } else { 0 });
1390            }
1391            OP_I32_CLZ => {
1392                let a: i32 = stack.pop().unwrap_or(0);
1393                stack.push(a.leading_zeros() as i32);
1394            }
1395            OP_I32_CTZ => {
1396                let a: i32 = stack.pop().unwrap_or(0);
1397                stack.push(a.trailing_zeros() as i32);
1398            }
1399            OP_I32_POPCNT => {
1400                let a: i32 = stack.pop().unwrap_or(0);
1401                stack.push(a.count_ones() as i32);
1402            }
1403            other => {
1404                if let Some(res) = eval_i32_binop(other, &mut stack)? {
1405                    stack.push(res);
1406                } else {
1407                    return Err(WasmDynamicError::ExecutionTrap(format!(
1408                        "unsupported wasm opcode 0x{other:02x}"
1409                    )));
1410                }
1411            }
1412        }
1413    }
1414    Ok(stack.pop().unwrap_or(0))
1415}
1416
1417/// Builds a genuine signed partial-slot `.wasm` binary rendering a rich native `DynamicNodeSpec` with live interactive state.
1418///
1419/// # Arguments
1420///
1421/// - `&str` - Display title rendered by the WASM widget.
1422/// - `u64` - Release version number.
1423/// - `u32` - Accent RGB hex color.
1424///
1425/// # Returns
1426///
1427/// - `Vec<u8>` - Spec-compliant executable `.wasm` binary bytes.
1428#[must_use]
1429pub fn build_partial_widget_wasm(title: &str, version: u64, accent_hex: u32) -> Vec<u8> {
1430    let mut badge: DynamicNodeSpec = DynamicNodeSpec::badge(format!("WASM v{version} · NATIVE"));
1431    badge
1432        .get_mut_style()
1433        .set_background_hex(Some(accent_hex))
1434        .set_color_hex(Some(0xFFFFFF));
1435    let mut heading: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
1436    heading
1437        .get_mut_style()
1438        .set_bold(true)
1439        .set_font_size(Some(14.0));
1440    let sub: DynamicNodeSpec = DynamicNodeSpec::text(format!(
1441        "Downloaded .wasm binary executed in sandboxed VM and rendered directly to native SceneTree (rev v{version}, state=0)."
1442    ));
1443    let mut btn_interact: DynamicNodeSpec = DynamicNodeSpec::button(
1444        "Invoke WASM euv_on_event (+1)".to_string(),
1445        "wasm_interact".to_string(),
1446    );
1447    btn_interact.get_mut_style().set_full_width(true);
1448    btn_interact.set_payload(format!("wasm-partial-v{version}"));
1449    let mut root_even: DynamicNodeSpec = DynamicNodeSpec::column()
1450        .child(
1451            DynamicNodeSpec::row()
1452                .child(badge.clone())
1453                .child(heading.clone()),
1454        )
1455        .child(sub)
1456        .child(btn_interact.clone());
1457    root_even
1458        .get_mut_style()
1459        .set_full_width(true)
1460        .set_padding(Some(14.0))
1461        .set_gap(Some(10.0))
1462        .set_radius(Some(10.0))
1463        .set_border_width(Some(1.0))
1464        .set_border_hex(Some(accent_hex));
1465    let sub_alt: DynamicNodeSpec = DynamicNodeSpec::text(format!(
1466        "Interactive WASM state toggled inside sandbox (rev v{version}, active pulse state=1) — zero host rebuild!"
1467    ));
1468    let mut root_odd: DynamicNodeSpec = DynamicNodeSpec::column()
1469        .child(DynamicNodeSpec::row().child(badge).child(heading))
1470        .child(sub_alt)
1471        .child(btn_interact);
1472    root_odd
1473        .get_mut_style()
1474        .set_full_width(true)
1475        .set_padding(Some(14.0))
1476        .set_gap(Some(10.0))
1477        .set_radius(Some(10.0))
1478        .set_background_hex(Some(0xECFDF5))
1479        .set_border_width(Some(1.0))
1480        .set_border_hex(Some(0x10B981));
1481    WasmModuleBuilder::partial_spec(&root_even)
1482        .with_alt_spec(&root_odd)
1483        .with_log(format!("partial wasm v{version} rendered natively"))
1484        .build()
1485}
1486
1487/// Builds one deterministic state bundle (`state_idx = 0 | 1`) embedded inside a global full-app `.wasm` release.
1488///
1489/// # Arguments
1490///
1491/// - `&str` - Global release title.
1492/// - `u64` - Monotonic global release version.
1493/// - `u8` - Interactive toggle state index (`0` or `1`).
1494///
1495/// # Returns
1496///
1497/// - `DynamicUpdateBundle` - Signed bundle targeting both global root component and page routes.
1498#[must_use]
1499fn build_global_state_bundle(title: &str, version: u64, state_idx: u8) -> DynamicUpdateBundle {
1500    let mut badge: DynamicNodeSpec =
1501        DynamicNodeSpec::badge(format!("GLOBAL WASM APP v{version} · STATE #{state_idx}"));
1502    badge
1503        .get_mut_style()
1504        .set_background_hex(Some(if state_idx == 0 { 0x0F766E } else { 0x1D4ED8 }))
1505        .set_color_hex(Some(0xFFFFFF));
1506    let mut hero_title: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
1507    hero_title
1508        .get_mut_style()
1509        .set_bold(true)
1510        .set_font_size(Some(20.0));
1511    let hero_sub: DynamicNodeSpec = DynamicNodeSpec::text(if state_idx == 0 {
1512        format!(
1513            "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."
1514        )
1515    } else {
1516        format!(
1517            "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."
1518        )
1519    });
1520    let mut kpi_col: DynamicNodeSpec =
1521        DynamicNodeSpec::column()
1522            .child(DynamicNodeSpec::card("Execution Mode".to_string()).child(
1523                DynamicNodeSpec::text("Sandboxed WASM -> Native SceneTree".to_string()),
1524            ))
1525            .child(
1526                DynamicNodeSpec::card("Integrity Gate".to_string())
1527                    .child(DynamicNodeSpec::text(format!("Verified Signed v{version}"))),
1528            )
1529            .child(
1530                DynamicNodeSpec::card("Safety Guard".to_string()).child(DynamicNodeSpec::text(
1531                    "Fuel + Memory + Atomic LKG Rollback".to_string(),
1532                )),
1533            );
1534    kpi_col
1535        .get_mut_style()
1536        .set_full_width(true)
1537        .set_gap(Some(10.0));
1538    let mut btn_action: DynamicNodeSpec = DynamicNodeSpec::button(
1539        "Invoke Global WASM Action (+1)".to_string(),
1540        "global_wasm_action".to_string(),
1541    );
1542    btn_action.get_mut_style().set_full_width(true);
1543    btn_action.set_payload(format!("global-v{version}-state-{state_idx}"));
1544    let mut btn_rollback: DynamicNodeSpec = DynamicNodeSpec::button(
1545        "Rollback Previous Version".to_string(),
1546        "global_wasm_rollback".to_string(),
1547    );
1548    btn_rollback
1549        .get_mut_style()
1550        .set_full_width(true)
1551        .set_background_hex(Some(0x334155))
1552        .set_color_hex(Some(0xFFFFFF));
1553    btn_rollback.set_payload("rollback-global".to_string());
1554    let mut btn_restore: DynamicNodeSpec = DynamicNodeSpec::button(
1555        "Return to Native Shell".to_string(),
1556        "global_wasm_restore".to_string(),
1557    );
1558    btn_restore
1559        .get_mut_style()
1560        .set_full_width(true)
1561        .set_background_hex(Some(0x0F766E))
1562        .set_color_hex(Some(0xFFFFFF));
1563    btn_restore.set_payload("restore-native".to_string());
1564    let mut action_row: DynamicNodeSpec = DynamicNodeSpec::column()
1565        .child(btn_action)
1566        .child(btn_rollback)
1567        .child(btn_restore);
1568    action_row
1569        .get_mut_style()
1570        .set_full_width(true)
1571        .set_gap(Some(10.0));
1572    let mut root_spec: DynamicNodeSpec = DynamicNodeSpec::column()
1573        .child(badge)
1574        .child(hero_title)
1575        .child(hero_sub)
1576        .child(action_row)
1577        .child(kpi_col);
1578    root_spec
1579        .get_mut_style()
1580        .set_full_width(true)
1581        .set_padding(Some(20.0))
1582        .set_gap(Some(14.0))
1583        .set_radius(Some(12.0))
1584        .set_background_hex(Some(if state_idx == 0 { 0xFFFFFF } else { 0xEFF6FF }))
1585        .set_border_width(Some(1.0))
1586        .set_border_hex(Some(if state_idx == 0 { 0x14B8A6 } else { 0x2563EB }));
1587    let mut global_comp: DynamicComponentUpdate = DynamicComponentUpdate::new(
1588        WASM_GLOBAL_ROOT_SLOT.to_string(),
1589        version,
1590        root_spec.clone(),
1591    );
1592    global_comp.set_allow_downgrade(true);
1593    global_comp.sign();
1594    let mut global_page: DynamicPageUpdate = DynamicPageUpdate::new(
1595        "/wasm-global-live".to_string(),
1596        format!("Global WASM v{version}"),
1597        version,
1598        root_spec,
1599    );
1600    global_page.set_allow_downgrade(true);
1601    global_page.sign();
1602    let mut bundle: DynamicUpdateBundle =
1603        DynamicUpdateBundle::new(format!("global-wasm-v{version}"), version);
1604    bundle.get_mut_components().push(global_comp);
1605    bundle.get_mut_pages().push(global_page);
1606    bundle
1607}
1608
1609/// Builds a genuine global full-app `.wasm` binary emitting a complete `DynamicUpdateBundle` that atomically takes over the root shell.
1610///
1611/// # Arguments
1612///
1613/// - `&str` - Global release title.
1614/// - `u64` - Monotonic global release version.
1615///
1616/// # Returns
1617///
1618/// - `Vec<u8>` - Spec-compliant executable global `.wasm` binary bytes.
1619#[must_use]
1620pub fn build_global_app_wasm(title: &str, version: u64) -> Vec<u8> {
1621    let bundle_even: DynamicUpdateBundle = build_global_state_bundle(title, version, 0);
1622    let bundle_odd: DynamicUpdateBundle = build_global_state_bundle(title, version, 1);
1623    WasmModuleBuilder::global_bundle(&bundle_even)
1624        .with_alt_bundle(&bundle_odd)
1625        .with_log(format!("global wasm bundle v{version} mounted natively"))
1626        .build()
1627}
1628
1629/// Builds a faulty `.wasm` binary exercising a specific security, integrity, ABI, or sandbox trap case.
1630///
1631/// # Arguments
1632///
1633/// - `WasmFaultKind` - Specific failure case to compile into the test binary.
1634///
1635/// # Returns
1636///
1637/// - `Vec<u8>` - Crafted `.wasm` binary bytes triggering `fault`.
1638#[must_use]
1639pub fn build_faulty_wasm(fault: WasmFaultKind) -> Vec<u8> {
1640    match fault {
1641        WasmFaultKind::CorruptedMagic => b"NOT_A_VALID_WASM_BINARY".to_vec(),
1642        WasmFaultKind::AbiMismatch => {
1643            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Incompatible ABI".to_string()))
1644                .with_abi_version(99)
1645                .build()
1646        }
1647        WasmFaultKind::MissingExport => {
1648            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Missing Export".to_string()))
1649                .without_render_export()
1650                .build()
1651        }
1652        WasmFaultKind::InfiniteLoopOutOfFuel => {
1653            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Infinite Loop".to_string()))
1654                .with_fault(WasmFaultKind::InfiniteLoopOutOfFuel)
1655                .build()
1656        }
1657        WasmFaultKind::ExecutionTrap => {
1658            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Trap".to_string()))
1659                .with_fault(WasmFaultKind::ExecutionTrap)
1660                .build()
1661        }
1662        WasmFaultKind::OversizedBinary => {
1663            let mut big: Vec<u8> = build_partial_widget_wasm("Oversized", 1, 0xDC2626);
1664            big.resize(WASM_DEFAULT_MAX_BINARY_BYTES + 64, 0);
1665            big
1666        }
1667        _ => build_partial_widget_wasm("Fault Fixture", 1, 0x2563EB),
1668    }
1669}