1use super::*;
2
3#[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#[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 b: u64 = byte as u64;
55 h1 = (h1 ^ b).wrapping_mul(FNV_PRIME);
56 h2 = h2.rotate_left(7) ^ b;
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 b: u64 = byte as u64;
76 h1 = (h1 ^ b).wrapping_mul(FNV_PRIME);
77 h2 = (h2 ^ b.wrapping_mul(SIG_MIX)).rotate_left(13);
78 }
79 format!("{WASM_SIGNATURE_PREFIX}{h1:016x}{h2:016x}")
80}
81
82pub(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
102pub(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
121pub(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
152pub(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
186fn 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
208pub 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 sc: usize = 0;
249 match sec_id {
250 WASM_SEC_CUSTOM => {
251 let sec_name: String = read_wasm_name(sec_slice, &mut sc)?;
252 let payload: Vec<u8> = sec_slice[sc..].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 sc)?;
257 for _ in 0..count {
258 let tag: u8 = *sec_slice.get(sc).ok_or_else(|| {
259 WasmDynamicError::InvalidWasmBinary("truncated type entry".to_string())
260 })?;
261 sc += 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 sc)? as usize;
268 sc = sc.saturating_add(params);
269 let results: usize = read_uleb128(sec_slice, &mut sc)? as usize;
270 sc = sc.saturating_add(results);
271 if sc > 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 sc)?;
283 for _ in 0..count {
284 let mod_name: String = read_wasm_name(sec_slice, &mut sc)?;
285 let field_name: String = read_wasm_name(sec_slice, &mut sc)?;
286 let kind: u8 = *sec_slice.get(sc).ok_or_else(|| {
287 WasmDynamicError::InvalidWasmBinary("truncated import kind".to_string())
288 })?;
289 sc += 1;
290 if kind == 0x00 {
291 let type_idx: u32 = read_uleb128(sec_slice, &mut sc)?;
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 sc)?;
304 for _ in 0..count {
305 func_type_indices.push(read_uleb128(sec_slice, &mut sc)?);
306 }
307 }
308 WASM_SEC_MEMORY => {
309 let count: u32 = read_uleb128(sec_slice, &mut sc)?;
310 if count > 0 {
311 let flags: u8 = *sec_slice.get(sc).ok_or_else(|| {
312 WasmDynamicError::InvalidWasmBinary("truncated memory limits".to_string())
313 })?;
314 sc += 1;
315 let min_pages: u32 = read_uleb128(sec_slice, &mut sc)?;
316 if (flags & 0x01) != 0 {
317 let _: u32 = read_uleb128(sec_slice, &mut sc)?;
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_EXPORT => {
330 let count: u32 = read_uleb128(sec_slice, &mut sc)?;
331 for _ in 0..count {
332 let exp_name: String = read_wasm_name(sec_slice, &mut sc)?;
333 let kind: u8 = *sec_slice.get(sc).ok_or_else(|| {
334 WasmDynamicError::InvalidWasmBinary("truncated export kind".to_string())
335 })?;
336 sc += 1;
337 let idx: u32 = read_uleb128(sec_slice, &mut sc)?;
338 if kind == 0x00 {
339 let _: Option<u32> = module.get_mut_exports().insert(exp_name, idx);
340 }
341 }
342 }
343 WASM_SEC_CODE => {
344 let count: usize = read_uleb128(sec_slice, &mut sc)? as usize;
345 if count != func_type_indices.len() {
346 return Err(WasmDynamicError::InvalidWasmBinary(
347 "function/code count mismatch".to_string(),
348 ));
349 }
350 for type_idx in func_type_indices.iter().copied() {
351 let body_len: usize = read_uleb128(sec_slice, &mut sc)? as usize;
352 let body_end: usize = sc.saturating_add(body_len);
353 if body_end > sec_slice.len() {
354 return Err(WasmDynamicError::InvalidWasmBinary(
355 "truncated code body".to_string(),
356 ));
357 }
358 let local_decl_groups: u32 = read_uleb128(sec_slice, &mut sc)?;
359 let mut extra_locals: usize = 0;
360 for _ in 0..local_decl_groups {
361 let lcount: usize = read_uleb128(sec_slice, &mut sc)? as usize;
362 sc = sc.saturating_add(1);
363 extra_locals = extra_locals.saturating_add(lcount);
364 }
365 if sc > body_end {
366 return Err(WasmDynamicError::InvalidWasmBinary(
367 "invalid local declarations".to_string(),
368 ));
369 }
370 let code: Vec<u8> = sec_slice[sc..body_end].to_vec();
371 let is_pure_no_mem: bool = wasm_body_is_pure_no_memory(code.as_slice());
372 sc = body_end;
373 let mut parsed_fn: WasmParsedFunction =
374 WasmParsedFunction::new(type_idx, extra_locals, code);
375 parsed_fn.set_pure_no_memory(is_pure_no_mem);
376 module.get_mut_functions().push(parsed_fn);
377 }
378 }
379 WASM_SEC_DATA => {
380 let count: u32 = read_uleb128(sec_slice, &mut sc)?;
381 for _ in 0..count {
382 let flags: u32 = read_uleb128(sec_slice, &mut sc)?;
383 if flags != 0 {
384 return Err(WasmDynamicError::InvalidWasmBinary(
385 "unsupported passive data segment".to_string(),
386 ));
387 }
388 let op: u8 = *sec_slice.get(sc).ok_or_else(|| {
389 WasmDynamicError::InvalidWasmBinary("truncated data offset".to_string())
390 })?;
391 sc += 1;
392 if op != OP_I32_CONST {
393 return Err(WasmDynamicError::InvalidWasmBinary(
394 "expected i32.const in data offset".to_string(),
395 ));
396 }
397 let offset: u32 = read_sleb128(sec_slice, &mut sc)?.max(0) as u32;
398 let end_op: u8 = *sec_slice.get(sc).ok_or_else(|| {
399 WasmDynamicError::InvalidWasmBinary(
400 "missing end in data offset".to_string(),
401 )
402 })?;
403 sc += 1;
404 if end_op != OP_END {
405 return Err(WasmDynamicError::InvalidWasmBinary(
406 "malformed data offset expr".to_string(),
407 ));
408 }
409 let data_len: usize = read_uleb128(sec_slice, &mut sc)? as usize;
410 let data_end: usize = sc.saturating_add(data_len);
411 if data_end > sec_slice.len() {
412 return Err(WasmDynamicError::InvalidWasmBinary(
413 "truncated data segment bytes".to_string(),
414 ));
415 }
416 let seg_bytes: Vec<u8> = sec_slice[sc..data_end].to_vec();
417 sc = data_end;
418 module
419 .get_mut_data_segments()
420 .push(WasmDataSegment::new(offset, seg_bytes));
421 }
422 }
423 _ => {}
424 }
425 }
426 if module.get_memory_min_pages() == 0 {
427 module.set_memory_min_pages(1);
428 }
429 Ok(module)
430}
431
432fn read_memory_str(memory: &[u8], ptr: u32, len: u32) -> Result<&str, WasmDynamicError> {
444 let start: usize = ptr as usize;
445 let end: usize = start.saturating_add(len as usize);
446 if end > memory.len() {
447 return Err(WasmDynamicError::MemoryOutOfBounds {
448 addr: ptr,
449 len,
450 memory_size: memory.len(),
451 });
452 }
453 from_utf8(&memory[start..end])
454 .map_err(|_| WasmDynamicError::InvalidUiPayload("non-UTF8 memory buffer".to_string()))
455}
456
457#[must_use]
467fn wasm_body_is_pure_no_memory(code: &[u8]) -> bool {
468 const MEMORY_OR_CALL_OPS: [u8; 3] = [OP_CALL, OP_I32_LOAD, OP_I32_STORE];
469 const BLOCK_OPS: [u8; 3] = [OP_BLOCK, OP_LOOP, OP_IF];
470 const ULEB_IMM_OPS: [u8; 4] = [OP_LOCAL_GET, OP_LOCAL_SET, OP_BR, OP_BR_IF];
471 const ZERO_IMM_OPS: [u8; 15] = [
472 OP_UNREACHABLE,
473 OP_NOP,
474 OP_ELSE,
475 OP_END,
476 OP_RETURN,
477 OP_DROP,
478 OP_I32_EQZ,
479 OP_I32_EQ,
480 OP_I32_NE,
481 OP_I32_LT_S,
482 OP_I32_GT_S,
483 OP_I32_ADD,
484 OP_I32_SUB,
485 OP_I32_MUL,
486 OP_I32_DIV_S,
487 ];
488 let mut pc: usize = 0;
489 while pc < code.len() {
490 let op: u8 = code[pc];
491 pc += 1;
492 if MEMORY_OR_CALL_OPS.contains(&op) {
493 return false;
494 }
495 if BLOCK_OPS.contains(&op) {
496 if pc >= code.len() {
497 return false;
498 }
499 pc += 1;
500 } else if op == OP_I32_CONST {
501 if read_sleb128(code, &mut pc).is_err() {
502 return false;
503 }
504 } else if ULEB_IMM_OPS.contains(&op) {
505 if read_uleb128(code, &mut pc).is_err() {
506 return false;
507 }
508 } else if !ZERO_IMM_OPS.contains(&op) {
509 return false;
510 }
511 }
512 true
513}
514
515fn execute_wasm_with_memory_slice(
529 module: &WasmParsedModule,
530 func_idx: u32,
531 args: &[i32],
532 config: &WasmSandboxConfig,
533 memory: &mut [u8],
534) -> (Result<WasmExecutionOutput, WasmDynamicError>, usize) {
535 let mut dirty_end: usize = 0;
536 for seg in module.get_data_segments().iter() {
537 let start: usize = seg.get_offset() as usize;
538 let end: usize = start.saturating_add(seg.get_bytes().len());
539 if end > memory.len() {
540 return (
541 Err(WasmDynamicError::MemoryOutOfBounds {
542 addr: seg.get_offset(),
543 len: seg.get_bytes().len() as u32,
544 memory_size: memory.len(),
545 }),
546 dirty_end,
547 );
548 }
549 memory[start..end].copy_from_slice(seg.get_bytes().as_slice());
550 if end > dirty_end {
551 dirty_end = end;
552 }
553 }
554 let mut out: WasmExecutionOutput = WasmExecutionOutput::default();
555 let mut exec: WasmExecContext<'_> = WasmExecContext {
556 memory,
557 out: &mut out,
558 fuel_used: 0,
559 max_fuel: config.get_max_fuel(),
560 depth: 0,
561 dirty_end,
562 };
563 let ret_res: Result<i32, WasmDynamicError> =
564 execute_wasm_func_index(module, func_idx, args, &mut exec);
565 let final_dirty: usize = exec.dirty_end;
566 let fuel_used: u64 = exec.fuel_used;
567 match ret_res {
568 Ok(ret) => {
569 out.set_return_value(ret);
570 out.set_fuel_used(fuel_used);
571 (Ok(out), final_dirty)
572 }
573 Err(err) => (Err(err), final_dirty),
574 }
575}
576
577pub fn execute_wasm_export(
590 module: &WasmParsedModule,
591 export_name: &str,
592 args: &[i32],
593 config: &WasmSandboxConfig,
594) -> Result<WasmExecutionOutput, WasmDynamicError> {
595 let func_idx: u32 = *module
596 .get_exports()
597 .get(export_name)
598 .ok_or_else(|| WasmDynamicError::MissingExport(export_name.to_string()))?;
599 let mem_bytes: usize =
600 (module.get_memory_min_pages().max(1) as usize).saturating_mul(WASM_PAGE_BYTES);
601 if mem_bytes > config.get_max_memory_bytes() {
602 return Err(WasmDynamicError::MemoryLimitExceeded {
603 requested: mem_bytes,
604 limit: config.get_max_memory_bytes(),
605 });
606 }
607 let import_count: usize = module.get_imports().len();
608 let is_pure_no_memory: bool = (func_idx as usize) >= import_count
609 && module
610 .get_functions()
611 .get((func_idx as usize) - import_count)
612 .is_some_and(WasmParsedFunction::get_pure_no_memory);
613 if is_pure_no_memory {
614 for seg in module.get_data_segments().iter() {
615 let start: usize = seg.get_offset() as usize;
616 let end: usize = start.saturating_add(seg.get_bytes().len());
617 if end > mem_bytes {
618 return Err(WasmDynamicError::MemoryOutOfBounds {
619 addr: seg.get_offset(),
620 len: seg.get_bytes().len() as u32,
621 memory_size: mem_bytes,
622 });
623 }
624 }
625 let mut out: WasmExecutionOutput = WasmExecutionOutput::default();
626 let mut empty_mem: [u8; 0] = [];
627 let mut exec: WasmExecContext<'_> = WasmExecContext {
628 memory: &mut empty_mem,
629 out: &mut out,
630 fuel_used: 0,
631 max_fuel: config.get_max_fuel(),
632 depth: 0,
633 dirty_end: 0,
634 };
635 let ret: i32 = execute_wasm_func_index(module, func_idx, args, &mut exec)?;
636 let fuel_used: u64 = exec.fuel_used;
637 out.set_return_value(ret);
638 out.set_fuel_used(fuel_used);
639 return Ok(out);
640 }
641 WASM_LINEAR_MEMORY_POOL.with(|cell: &RefCell<WasmMemoryPool>| {
642 if let Ok(mut pool) = cell.try_borrow_mut() {
643 if pool.buffer.len() < mem_bytes {
644 pool.buffer.resize(mem_bytes, 0);
645 }
646 let (res, dirty_end): (Result<WasmExecutionOutput, WasmDynamicError>, usize) =
647 execute_wasm_with_memory_slice(
648 module,
649 func_idx,
650 args,
651 config,
652 &mut pool.buffer[..mem_bytes],
653 );
654 let clear_len: usize = dirty_end.min(pool.buffer.len());
655 if clear_len > 0 {
656 pool.buffer[..clear_len].fill(0);
657 }
658 let max_retained_bytes: usize = WASM_PAGE_BYTES.saturating_mul(4);
659 if pool.buffer.len() > max_retained_bytes {
660 pool.buffer.truncate(max_retained_bytes);
661 pool.buffer.shrink_to_fit();
662 }
663 res
664 } else {
665 let mut local_mem: Vec<u8> = vec![0; mem_bytes];
666 let (res, _): (Result<WasmExecutionOutput, WasmDynamicError>, usize) =
667 execute_wasm_with_memory_slice(
668 module,
669 func_idx,
670 args,
671 config,
672 local_mem.as_mut_slice(),
673 );
674 res
675 }
676 })
677}
678
679fn eval_i32_binop(op: u8, stack: &mut Vec<i32>) -> Result<Option<i32>, WasmDynamicError> {
690 let is_binop: bool = op == OP_I32_EQ
691 || op == OP_I32_NE
692 || op == OP_I32_LT_S
693 || op == OP_I32_GT_S
694 || op == OP_I32_ADD
695 || op == OP_I32_SUB
696 || op == OP_I32_MUL
697 || op == OP_I32_DIV_S;
698 if !is_binop {
699 return Ok(None);
700 }
701 let b: i32 = stack
702 .pop()
703 .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
704 let a: i32 = stack
705 .pop()
706 .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
707 let res: i32 = match op {
708 OP_I32_EQ => i32::from(a == b),
709 OP_I32_NE => i32::from(a != b),
710 OP_I32_LT_S => i32::from(a < b),
711 OP_I32_GT_S => i32::from(a > b),
712 OP_I32_ADD => a.wrapping_add(b),
713 OP_I32_SUB => a.wrapping_sub(b),
714 OP_I32_MUL => a.wrapping_mul(b),
715 OP_I32_DIV_S => {
716 if b == 0 {
717 return Err(WasmDynamicError::ExecutionTrap(
718 "integer divide by zero".to_string(),
719 ));
720 }
721 a.wrapping_div(b)
722 }
723 _ => 0,
724 };
725 Ok(Some(res))
726}
727
728fn execute_wasm_func_index(
741 module: &WasmParsedModule,
742 func_idx: u32,
743 args: &[i32],
744 exec: &mut WasmExecContext<'_>,
745) -> Result<i32, WasmDynamicError> {
746 if exec.depth > 32 {
747 return Err(WasmDynamicError::ExecutionTrap(
748 "call stack depth overflow".to_string(),
749 ));
750 }
751 let import_count: usize = module.get_imports().len();
752 if (func_idx as usize) < import_count {
753 let imp: &WasmImportEntry = &module.get_imports()[func_idx as usize];
754 let ptr: u32 = args.first().copied().unwrap_or(0).max(0) as u32;
755 let len: u32 = args.get(1).copied().unwrap_or(0).max(0) as u32;
756 let text: &str = read_memory_str(exec.memory, ptr, len)?;
757 if imp.get_name() == WASM_IMPORT_EMIT_UI {
758 let spec: DynamicNodeSpec =
759 from_str::<DynamicNodeSpec>(text).map_err(|err: serde_json::Error| {
760 WasmDynamicError::InvalidUiPayload(err.to_string())
761 })?;
762 exec.out.set_emitted_spec(Some(spec));
763 return Ok(1);
764 }
765 if imp.get_name() == WASM_IMPORT_EMIT_BUNDLE {
766 let bundle: DynamicUpdateBundle =
767 from_str::<DynamicUpdateBundle>(text).map_err(|err: serde_json::Error| {
768 WasmDynamicError::InvalidUiPayload(err.to_string())
769 })?;
770 exec.out.set_emitted_bundle(Some(bundle));
771 return Ok(1);
772 }
773 if imp.get_name() == WASM_IMPORT_LOG {
774 exec.out.get_mut_logs().push(text.to_string());
775 return Ok(1);
776 }
777 return Err(WasmDynamicError::ExecutionTrap(format!(
778 "unknown host import {}::{}",
779 imp.get_module(),
780 imp.get_name()
781 )));
782 }
783 let local_idx: usize = (func_idx as usize) - import_count;
784 let func: &WasmParsedFunction = module
785 .get_functions()
786 .get(local_idx)
787 .ok_or_else(|| WasmDynamicError::ExecutionTrap("invalid function index".to_string()))?;
788 let sig: WasmFuncSignature = module
789 .get_types()
790 .get(func.get_type_index() as usize)
791 .copied()
792 .unwrap_or_default();
793 let total_locals: usize = sig
794 .get_param_count()
795 .saturating_add(func.get_extra_locals())
796 .max(args.len());
797 let mut inline_locals: [i32; 16] = [0; 16];
798 let mut spill_locals: Vec<i32> = if total_locals > inline_locals.len() {
799 vec![0; total_locals]
800 } else {
801 Vec::new()
802 };
803 let locals: &mut [i32] = if spill_locals.is_empty() {
804 &mut inline_locals[..total_locals]
805 } else {
806 spill_locals.as_mut_slice()
807 };
808 for (idx, val) in args.iter().copied().enumerate() {
809 if idx < locals.len() {
810 locals[idx] = val;
811 }
812 }
813 let code: &[u8] = func.get_body().as_slice();
814 let mut stack: Vec<i32> = Vec::with_capacity(32);
815 let mut labels: Vec<(u8, usize)> = Vec::with_capacity(16);
816 let mut pc: usize = 0;
817 while pc < code.len() {
818 exec.fuel_used = exec.fuel_used.saturating_add(1);
819 if exec.fuel_used > exec.max_fuel {
820 return Err(WasmDynamicError::OutOfFuel {
821 limit: exec.max_fuel,
822 });
823 }
824 let op: u8 = code[pc];
825 pc += 1;
826 match op {
827 OP_UNREACHABLE => {
828 return Err(WasmDynamicError::ExecutionTrap(
829 "wasm unreachable instruction trapped".to_string(),
830 ));
831 }
832 OP_NOP => {}
833 OP_BLOCK | OP_LOOP => {
834 let _: u8 = *code.get(pc).unwrap_or(&0x40);
835 pc = pc.saturating_add(1);
836 labels.push((op, pc));
837 }
838 OP_IF => {
839 let _: u8 = *code.get(pc).unwrap_or(&0x40);
840 pc = pc.saturating_add(1);
841 let cond: i32 = stack.pop().ok_or_else(|| {
842 WasmDynamicError::ExecutionTrap("stack underflow on if".to_string())
843 })?;
844 if cond != 0 {
845 labels.push((OP_IF, pc));
846 } else {
847 let mut nesting: usize = 0;
848 while pc < code.len() {
849 let scan: u8 = code[pc];
850 pc += 1;
851 if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
852 nesting += 1;
853 pc = pc.saturating_add(1);
854 } else if scan == OP_ELSE && nesting == 0 {
855 labels.push((OP_ELSE, pc));
856 break;
857 } else if scan == OP_END {
858 if nesting == 0 {
859 break;
860 }
861 nesting -= 1;
862 } else if scan == OP_I32_CONST {
863 let _: i32 = read_sleb128(code, &mut pc)?;
864 } else if scan == OP_LOCAL_GET
865 || scan == OP_LOCAL_SET
866 || scan == OP_CALL
867 || scan == OP_BR
868 || scan == OP_BR_IF
869 {
870 let _: u32 = read_uleb128(code, &mut pc)?;
871 } else if scan == OP_I32_LOAD || scan == OP_I32_STORE {
872 let _: u32 = read_uleb128(code, &mut pc)?;
873 let _: u32 = read_uleb128(code, &mut pc)?;
874 }
875 }
876 }
877 }
878 OP_ELSE => {
879 let _: Option<(u8, usize)> = labels.pop();
880 let mut nesting: usize = 0;
881 while pc < code.len() {
882 let scan: u8 = code[pc];
883 pc += 1;
884 if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
885 nesting += 1;
886 pc = pc.saturating_add(1);
887 } else if scan == OP_END {
888 if nesting == 0 {
889 break;
890 }
891 nesting -= 1;
892 } else if scan == OP_I32_CONST {
893 let _: i32 = read_sleb128(code, &mut pc)?;
894 } else if scan == OP_LOCAL_GET
895 || scan == OP_LOCAL_SET
896 || scan == OP_CALL
897 || scan == OP_BR
898 || scan == OP_BR_IF
899 {
900 let _: u32 = read_uleb128(code, &mut pc)?;
901 } else if scan == OP_I32_LOAD || scan == OP_I32_STORE {
902 let _: u32 = read_uleb128(code, &mut pc)?;
903 let _: u32 = read_uleb128(code, &mut pc)?;
904 }
905 }
906 }
907 OP_END => {
908 if labels.pop().is_none() {
909 break;
910 }
911 }
912 OP_BR | OP_BR_IF => {
913 let target_depth: usize = read_uleb128(code, &mut pc)? as usize;
914 let take_branch: bool = if op == OP_BR_IF {
915 stack.pop().unwrap_or(0) != 0
916 } else {
917 true
918 };
919 if take_branch {
920 if target_depth >= labels.len() {
921 break;
922 }
923 let keep_len: usize = labels.len() - target_depth;
924 let (lbl_op, lbl_pc): (u8, usize) = labels[keep_len - 1];
925 if lbl_op == OP_LOOP {
926 labels.truncate(keep_len);
927 pc = lbl_pc;
928 } else {
929 labels.truncate(keep_len - 1);
930 let mut nesting: usize = 0;
931 while pc < code.len() {
932 let scan: u8 = code[pc];
933 pc += 1;
934 if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
935 nesting += 1;
936 pc = pc.saturating_add(1);
937 } else if scan == OP_END {
938 if nesting == 0 {
939 break;
940 }
941 nesting -= 1;
942 }
943 }
944 }
945 }
946 }
947 OP_RETURN => break,
948 OP_CALL => {
949 let callee: u32 = read_uleb128(code, &mut pc)?;
950 let callee_type: u32 = if (callee as usize) < import_count {
951 module.get_imports()[callee as usize].get_type_index()
952 } else {
953 module
954 .get_functions()
955 .get((callee as usize) - import_count)
956 .map(WasmParsedFunction::get_type_index)
957 .unwrap_or(0)
958 };
959 let csig: WasmFuncSignature = module
960 .get_types()
961 .get(callee_type as usize)
962 .copied()
963 .unwrap_or_default();
964 let param_count: usize = csig.get_param_count();
965 let mut inline_args: [i32; 8] = [0; 8];
966 let mut spill_args: Vec<i32> = if param_count > inline_args.len() {
967 vec![0; param_count]
968 } else {
969 Vec::new()
970 };
971 let call_args: &mut [i32] = if spill_args.is_empty() {
972 &mut inline_args[..param_count]
973 } else {
974 spill_args.as_mut_slice()
975 };
976 for idx in (0..param_count).rev() {
977 call_args[idx] = stack.pop().ok_or_else(|| {
978 WasmDynamicError::ExecutionTrap("stack underflow on call".to_string())
979 })?;
980 }
981 exec.depth = exec.depth.saturating_add(1);
982 let call_res: Result<i32, WasmDynamicError> =
983 execute_wasm_func_index(module, callee, call_args, exec);
984 exec.depth = exec.depth.saturating_sub(1);
985 let call_ret: i32 = call_res?;
986 if csig.get_result_count() > 0 {
987 stack.push(call_ret);
988 }
989 }
990 OP_DROP => {
991 let _: Option<i32> = stack.pop();
992 }
993 OP_LOCAL_GET => {
994 let idx: usize = read_uleb128(code, &mut pc)? as usize;
995 let val: i32 = *locals.get(idx).unwrap_or(&0);
996 stack.push(val);
997 }
998 OP_LOCAL_SET => {
999 let idx: usize = read_uleb128(code, &mut pc)? as usize;
1000 let val: i32 = stack.pop().ok_or_else(|| {
1001 WasmDynamicError::ExecutionTrap("stack underflow on local.set".to_string())
1002 })?;
1003 if idx < locals.len() {
1004 locals[idx] = val;
1005 }
1006 }
1007 OP_I32_LOAD => {
1008 let _: u32 = read_uleb128(code, &mut pc)?;
1009 let offset: u32 = read_uleb128(code, &mut pc)?;
1010 let base: u32 = stack.pop().unwrap_or(0).max(0) as u32;
1011 let addr: usize = (base.saturating_add(offset)) as usize;
1012 if addr.saturating_add(4) > exec.memory.len() {
1013 return Err(WasmDynamicError::MemoryOutOfBounds {
1014 addr: addr as u32,
1015 len: 4,
1016 memory_size: exec.memory.len(),
1017 });
1018 }
1019 let val: i32 = i32::from_le_bytes([
1020 exec.memory[addr],
1021 exec.memory[addr + 1],
1022 exec.memory[addr + 2],
1023 exec.memory[addr + 3],
1024 ]);
1025 stack.push(val);
1026 }
1027 OP_I32_STORE => {
1028 let _: u32 = read_uleb128(code, &mut pc)?;
1029 let offset: u32 = read_uleb128(code, &mut pc)?;
1030 let val: i32 = stack.pop().unwrap_or(0);
1031 let base: u32 = stack.pop().unwrap_or(0).max(0) as u32;
1032 let addr: usize = (base.saturating_add(offset)) as usize;
1033 if addr.saturating_add(4) > exec.memory.len() {
1034 return Err(WasmDynamicError::MemoryOutOfBounds {
1035 addr: addr as u32,
1036 len: 4,
1037 memory_size: exec.memory.len(),
1038 });
1039 }
1040 let write_end: usize = addr + 4;
1041 exec.memory[addr..write_end].copy_from_slice(&val.to_le_bytes());
1042 if write_end > exec.dirty_end {
1043 exec.dirty_end = write_end;
1044 }
1045 }
1046 OP_I32_CONST => {
1047 let val: i32 = read_sleb128(code, &mut pc)?;
1048 stack.push(val);
1049 }
1050 OP_I32_EQZ => {
1051 let a: i32 = stack.pop().unwrap_or(0);
1052 stack.push(if a == 0 { 1 } else { 0 });
1053 }
1054 other => {
1055 if let Some(res) = eval_i32_binop(other, &mut stack)? {
1056 stack.push(res);
1057 } else {
1058 return Err(WasmDynamicError::ExecutionTrap(format!(
1059 "unsupported wasm opcode 0x{other:02x}"
1060 )));
1061 }
1062 }
1063 }
1064 }
1065 Ok(stack.pop().unwrap_or(0))
1066}
1067
1068#[must_use]
1080pub fn build_partial_widget_wasm(title: &str, version: u64, accent_hex: u32) -> Vec<u8> {
1081 let mut badge: DynamicNodeSpec = DynamicNodeSpec::badge(format!("WASM v{version} · NATIVE"));
1082 badge
1083 .get_mut_style()
1084 .set_background_hex(Some(accent_hex))
1085 .set_color_hex(Some(0xFFFFFF));
1086 let mut heading: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
1087 heading
1088 .get_mut_style()
1089 .set_bold(true)
1090 .set_font_size(Some(14.0));
1091 let sub: DynamicNodeSpec = DynamicNodeSpec::text(format!(
1092 "Downloaded .wasm binary executed in sandboxed VM and rendered directly to native SceneTree (rev v{version}, state=0)."
1093 ));
1094 let mut btn_interact: DynamicNodeSpec = DynamicNodeSpec::button(
1095 "Invoke WASM euv_on_event (+1)".to_string(),
1096 "wasm_interact".to_string(),
1097 );
1098 btn_interact.get_mut_style().set_full_width(true);
1099 btn_interact.set_payload(format!("wasm-partial-v{version}"));
1100 let mut root_even: DynamicNodeSpec = DynamicNodeSpec::column()
1101 .child(
1102 DynamicNodeSpec::row()
1103 .child(badge.clone())
1104 .child(heading.clone()),
1105 )
1106 .child(sub)
1107 .child(btn_interact.clone());
1108 root_even
1109 .get_mut_style()
1110 .set_full_width(true)
1111 .set_padding(Some(14.0))
1112 .set_gap(Some(10.0))
1113 .set_radius(Some(10.0))
1114 .set_border_width(Some(1.0))
1115 .set_border_hex(Some(accent_hex));
1116 let sub_alt: DynamicNodeSpec = DynamicNodeSpec::text(format!(
1117 "Interactive WASM state toggled inside sandbox (rev v{version}, active pulse state=1) — zero host rebuild!"
1118 ));
1119 let mut root_odd: DynamicNodeSpec = DynamicNodeSpec::column()
1120 .child(DynamicNodeSpec::row().child(badge).child(heading))
1121 .child(sub_alt)
1122 .child(btn_interact);
1123 root_odd
1124 .get_mut_style()
1125 .set_full_width(true)
1126 .set_padding(Some(14.0))
1127 .set_gap(Some(10.0))
1128 .set_radius(Some(10.0))
1129 .set_background_hex(Some(0xECFDF5))
1130 .set_border_width(Some(1.0))
1131 .set_border_hex(Some(0x10B981));
1132 WasmModuleBuilder::partial_spec(&root_even)
1133 .with_alt_spec(&root_odd)
1134 .with_log(format!("partial wasm v{version} rendered natively"))
1135 .build()
1136}
1137
1138#[must_use]
1150fn build_global_state_bundle(title: &str, version: u64, state_idx: u8) -> DynamicUpdateBundle {
1151 let mut badge: DynamicNodeSpec =
1152 DynamicNodeSpec::badge(format!("GLOBAL WASM APP v{version} · STATE #{state_idx}"));
1153 badge
1154 .get_mut_style()
1155 .set_background_hex(Some(if state_idx == 0 { 0x0F766E } else { 0x1D4ED8 }))
1156 .set_color_hex(Some(0xFFFFFF));
1157 let mut hero_title: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
1158 hero_title
1159 .get_mut_style()
1160 .set_bold(true)
1161 .set_font_size(Some(20.0));
1162 let hero_sub: DynamicNodeSpec = DynamicNodeSpec::text(if state_idx == 0 {
1163 format!(
1164 "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."
1165 )
1166 } else {
1167 format!(
1168 "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."
1169 )
1170 });
1171 let mut kpi_col: DynamicNodeSpec =
1172 DynamicNodeSpec::column()
1173 .child(DynamicNodeSpec::card("Execution Mode".to_string()).child(
1174 DynamicNodeSpec::text("Sandboxed WASM -> Native SceneTree".to_string()),
1175 ))
1176 .child(
1177 DynamicNodeSpec::card("Integrity Gate".to_string())
1178 .child(DynamicNodeSpec::text(format!("Verified Signed v{version}"))),
1179 )
1180 .child(
1181 DynamicNodeSpec::card("Safety Guard".to_string()).child(DynamicNodeSpec::text(
1182 "Fuel + Memory + Atomic LKG Rollback".to_string(),
1183 )),
1184 );
1185 kpi_col
1186 .get_mut_style()
1187 .set_full_width(true)
1188 .set_gap(Some(10.0));
1189 let mut btn_action: DynamicNodeSpec = DynamicNodeSpec::button(
1190 "Invoke Global WASM Action (+1)".to_string(),
1191 "global_wasm_action".to_string(),
1192 );
1193 btn_action.get_mut_style().set_full_width(true);
1194 btn_action.set_payload(format!("global-v{version}-state-{state_idx}"));
1195 let mut btn_rollback: DynamicNodeSpec = DynamicNodeSpec::button(
1196 "Rollback Previous Version".to_string(),
1197 "global_wasm_rollback".to_string(),
1198 );
1199 btn_rollback
1200 .get_mut_style()
1201 .set_full_width(true)
1202 .set_background_hex(Some(0x334155))
1203 .set_color_hex(Some(0xFFFFFF));
1204 btn_rollback.set_payload("rollback-global".to_string());
1205 let mut btn_restore: DynamicNodeSpec = DynamicNodeSpec::button(
1206 "Return to Native Shell".to_string(),
1207 "global_wasm_restore".to_string(),
1208 );
1209 btn_restore
1210 .get_mut_style()
1211 .set_full_width(true)
1212 .set_background_hex(Some(0x0F766E))
1213 .set_color_hex(Some(0xFFFFFF));
1214 btn_restore.set_payload("restore-native".to_string());
1215 let mut action_row: DynamicNodeSpec = DynamicNodeSpec::column()
1216 .child(btn_action)
1217 .child(btn_rollback)
1218 .child(btn_restore);
1219 action_row
1220 .get_mut_style()
1221 .set_full_width(true)
1222 .set_gap(Some(10.0));
1223 let mut root_spec: DynamicNodeSpec = DynamicNodeSpec::column()
1224 .child(badge)
1225 .child(hero_title)
1226 .child(hero_sub)
1227 .child(action_row)
1228 .child(kpi_col);
1229 root_spec
1230 .get_mut_style()
1231 .set_full_width(true)
1232 .set_padding(Some(20.0))
1233 .set_gap(Some(14.0))
1234 .set_radius(Some(12.0))
1235 .set_background_hex(Some(if state_idx == 0 { 0xFFFFFF } else { 0xEFF6FF }))
1236 .set_border_width(Some(1.0))
1237 .set_border_hex(Some(if state_idx == 0 { 0x14B8A6 } else { 0x2563EB }));
1238 let mut global_comp: DynamicComponentUpdate = DynamicComponentUpdate::new(
1239 WASM_GLOBAL_ROOT_SLOT.to_string(),
1240 version,
1241 root_spec.clone(),
1242 );
1243 global_comp.set_allow_downgrade(true);
1244 global_comp.sign();
1245 let mut global_page: DynamicPageUpdate = DynamicPageUpdate::new(
1246 "/wasm-global-live".to_string(),
1247 format!("Global WASM v{version}"),
1248 version,
1249 root_spec,
1250 );
1251 global_page.set_allow_downgrade(true);
1252 global_page.sign();
1253 let mut bundle: DynamicUpdateBundle =
1254 DynamicUpdateBundle::new(format!("global-wasm-v{version}"), version);
1255 bundle.get_mut_components().push(global_comp);
1256 bundle.get_mut_pages().push(global_page);
1257 bundle
1258}
1259
1260#[must_use]
1271pub fn build_global_app_wasm(title: &str, version: u64) -> Vec<u8> {
1272 let bundle_even: DynamicUpdateBundle = build_global_state_bundle(title, version, 0);
1273 let bundle_odd: DynamicUpdateBundle = build_global_state_bundle(title, version, 1);
1274 WasmModuleBuilder::global_bundle(&bundle_even)
1275 .with_alt_bundle(&bundle_odd)
1276 .with_log(format!("global wasm bundle v{version} mounted natively"))
1277 .build()
1278}
1279
1280#[must_use]
1290pub fn build_faulty_wasm(fault: WasmFaultKind) -> Vec<u8> {
1291 match fault {
1292 WasmFaultKind::CorruptedMagic => b"NOT_A_VALID_WASM_BINARY".to_vec(),
1293 WasmFaultKind::AbiMismatch => {
1294 WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Incompatible ABI".to_string()))
1295 .with_abi_version(99)
1296 .build()
1297 }
1298 WasmFaultKind::MissingExport => {
1299 WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Missing Export".to_string()))
1300 .without_render_export()
1301 .build()
1302 }
1303 WasmFaultKind::InfiniteLoopOutOfFuel => {
1304 WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Infinite Loop".to_string()))
1305 .with_fault(WasmFaultKind::InfiniteLoopOutOfFuel)
1306 .build()
1307 }
1308 WasmFaultKind::ExecutionTrap => {
1309 WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Trap".to_string()))
1310 .with_fault(WasmFaultKind::ExecutionTrap)
1311 .build()
1312 }
1313 WasmFaultKind::OversizedBinary => {
1314 let mut big: Vec<u8> = build_partial_widget_wasm("Oversized", 1, 0xDC2626);
1315 big.resize(WASM_DEFAULT_MAX_BINARY_BYTES + 64, 0);
1316 big
1317 }
1318 _ => build_partial_widget_wasm("Fault Fixture", 1, 0x2563EB),
1319 }
1320}