1#[allow(
30 unused_imports,
31 clippy::wildcard_imports,
32 reason = "Standard workspace module prelude"
33)]
34use crate::utilities::*;
35
36use std::sync::{Arc, Mutex};
37
38use anyhow::anyhow;
39use ctb_formats_dcdata::tinywasm::types::{
40 ConstInstruction, DataKind, ElementItem, ExternalKind, FuncType, Global,
41 Import, ImportKind, Instruction, MemoryArch, TinyWasmModule,
42};
43
44use crate::BootstrapKernelVersion;
45
46use super::wasm::{DcWasmResourceLimits, WasmResourceInterruption};
47
48pub const CTB_QUOTA_REMAINING_EXPORT: &str = "__ctb_quota_remaining";
50pub const CTB_QUOTA_CONSUMED_EXPORT: &str = "__ctb_quota_consumed";
52pub const CTB_EXHAUSTED_EXPORT: &str = "__ctb_exhausted";
55pub const CTB_INTERRUPTED_OP_EXPORT: &str = "__ctb_interrupted_op";
58pub const CTB_REQUIRED_COST_EXPORT: &str = "__ctb_required_cost";
60pub const CTB_OP_ORDINAL_EXPORT: &str = "__ctb_op_ordinal";
62pub const CTB_TOTAL_MEM_PAGES_EXPORT: &str = "__ctb_total_mem_pages";
64pub const CTB_MAX_MEM_PAGES_EXPORT: &str = "__ctb_max_mem_pages";
66pub const CTB_PHYS_MAX_MEM_PAGES_EXPORT: &str = "__ctb_phys_max_mem_pages";
68pub const CTB_TOTAL_TABLE_ELEMS_EXPORT: &str = "__ctb_total_table_elems";
70pub const CTB_MAX_TABLE_ELEMS_EXPORT: &str = "__ctb_max_table_elems";
72pub const CTB_PHYS_MAX_TABLE_ELEMS_EXPORT: &str = "__ctb_phys_max_table_elems";
74pub const CTB_RESUME_TARGET_OP_EXPORT: &str = "__ctb_resume_target_op";
77pub const CTB_WASM_START_EXPORT: &str = "__ctb_wasm_start";
80pub const CTB_HOST_IMPORT_MODULE: &str = "__ctb_host";
84pub const CTB_HOST_SUSPEND_IMPORT_NAME: &str = "__ctb_suspend_on_quota";
87pub const CTB_HOST_CAPABILITY_IMPORT_NAME: &str = "__ctb_request_capability";
90pub const CTB_CAPABILITY_YIELD_EXPORT: &str = "__ctb_capability_yield";
93
94pub(crate) const WASM_HEADER: [u8; 8] =
95 [0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00];
96
97#[allow(
98 dead_code,
99 reason = "Full WASM section id table shared across wasm_quota and wasm_to_rust"
100)]
101pub(crate) const SEC_CUSTOM: u8 = 0;
102pub(crate) const SEC_TYPE: u8 = 1;
103pub(crate) const SEC_IMPORT: u8 = 2;
104pub(crate) const SEC_FUNCTION: u8 = 3;
105pub(crate) const SEC_TABLE: u8 = 4;
106pub(crate) const SEC_MEMORY: u8 = 5;
107pub(crate) const SEC_GLOBAL: u8 = 6;
108pub(crate) const SEC_EXPORT: u8 = 7;
109pub(crate) const SEC_START: u8 = 8;
110pub(crate) const SEC_ELEMENT: u8 = 9;
111pub(crate) const SEC_CODE: u8 = 10;
112pub(crate) const SEC_DATA: u8 = 11;
113pub(crate) const SEC_DATA_COUNT: u8 = 12;
114
115pub(crate) const VALTYPE_I32: u8 = 0x7F;
116pub(crate) const VALTYPE_I64: u8 = 0x7E;
117
118const MAX_CLAMPED_DECLARED_TABLE_ELEMENTS: u32 = 10_000_000;
123
124const TABLE_GROW_DENIAL_SENTINEL_DELTA: i32 = 0x4000_0000;
126
127#[derive(Debug, Clone)]
129pub struct InstrumentedWasmModule {
130 pub wasm_bytes: Vec<u8>,
133 pub parsed_instrumented: TinyWasmModule,
135 pub parsed_suspendable: TinyWasmModule,
138 pub has_start_func: bool,
141 pub initial_memory_pages: usize,
143 pub initial_table_elements: usize,
145 pub static_data_end: usize,
147 pub num_guest_globals: usize,
149 pub num_memories: usize,
151 pub num_tables: usize,
153}
154
155#[derive(Debug, Clone)]
157pub struct SharedWasmTaskQuotaState {
158 pub active_limits: DcWasmResourceLimits,
160 pub staged_boundary_limits: Option<DcWasmResourceLimits>,
163 pub grant_epoch: u64,
166 pub remaining_compute_quota: u64,
168 pub current_compute_quota_limit: u64,
170 pub total_instructions_executed: u64,
172 pub cumulative_output_bytes: usize,
174 pub max_session_output_bytes: usize,
176 pub last_resource_interruption: Option<WasmResourceInterruption>,
178}
179
180#[derive(Debug, Clone)]
184pub struct SharedWasmTaskQuota {
185 inner: Arc<Mutex<SharedWasmTaskQuotaState>>,
186}
187
188impl SharedWasmTaskQuota {
189 #[must_use]
191 pub fn new(limits: DcWasmResourceLimits) -> Self {
192 Self {
193 inner: Arc::new(Mutex::new(SharedWasmTaskQuotaState {
194 active_limits: limits,
195 staged_boundary_limits: None,
196 grant_epoch: 0,
197 remaining_compute_quota: limits.max_instructions_per_step,
198 current_compute_quota_limit: limits.max_instructions_per_step,
199 total_instructions_executed: 0,
200 cumulative_output_bytes: 0,
201 max_session_output_bytes: limits.max_session_output_bytes,
202 last_resource_interruption: None,
203 })),
204 }
205 }
206
207 pub fn active_limits(&self) -> Result<DcWasmResourceLimits> {
212 let guard = self
213 .inner
214 .lock()
215 .map_err(|_| anyhow!("SharedWasmTaskQuota mutex poisoned"))?;
216 Ok(guard.active_limits)
217 }
218
219 pub fn increase_compute_quota(&self, additional_units: u64) -> Result<u64> {
224 let mut guard = self
225 .inner
226 .lock()
227 .map_err(|_| anyhow!("SharedWasmTaskQuota mutex poisoned"))?;
228 guard.remaining_compute_quota = guard
229 .remaining_compute_quota
230 .saturating_add(additional_units);
231 guard.current_compute_quota_limit = guard
232 .current_compute_quota_limit
233 .saturating_add(additional_units);
234 guard.active_limits.max_instructions_per_step =
235 guard.current_compute_quota_limit;
236 guard.grant_epoch = guard.grant_epoch.saturating_add(1);
237 Ok(guard.grant_epoch)
238 }
239
240 pub fn stage_boundary_limits(
247 &self,
248 next_limits: DcWasmResourceLimits,
249 ) -> Result<()> {
250 let mut guard = self
251 .inner
252 .lock()
253 .map_err(|_| anyhow!("SharedWasmTaskQuota mutex poisoned"))?;
254 guard.staged_boundary_limits = Some(next_limits);
255 Ok(())
256 }
257
258 pub fn apply_staged_boundary_limits(
264 &self,
265 ) -> Result<Option<(DcWasmResourceLimits, u64)>> {
266 let mut guard = self
267 .inner
268 .lock()
269 .map_err(|_| anyhow!("SharedWasmTaskQuota mutex poisoned"))?;
270 let Some(next_limits) = guard.staged_boundary_limits.take() else {
271 return Ok(None);
272 };
273 guard.active_limits = next_limits;
274 guard.current_compute_quota_limit =
275 next_limits.max_instructions_per_step;
276 guard.remaining_compute_quota = next_limits
277 .max_instructions_per_step
278 .saturating_sub(guard.total_instructions_executed);
279 guard.max_session_output_bytes = next_limits.max_session_output_bytes;
280 guard.grant_epoch = guard.grant_epoch.saturating_add(1);
281 Ok(Some((next_limits, guard.grant_epoch)))
282 }
283
284 pub fn allocate_child_task_quota(
293 &self,
294 requested_compute_quota: u64,
295 requested_output_bytes: usize,
296 ) -> Result<(Self, u64)> {
297 let mut guard = self
298 .inner
299 .lock()
300 .map_err(|_| anyhow!("SharedWasmTaskQuota mutex poisoned"))?;
301 let granted_compute =
302 requested_compute_quota.min(guard.remaining_compute_quota);
303 let remaining_output_budget = guard
304 .max_session_output_bytes
305 .saturating_sub(guard.cumulative_output_bytes);
306 let granted_output = requested_output_bytes.min(remaining_output_budget);
307
308 guard.remaining_compute_quota = guard
309 .remaining_compute_quota
310 .saturating_sub(granted_compute);
311 guard.grant_epoch = guard.grant_epoch.saturating_add(1);
312 let epoch = guard.grant_epoch;
313
314 let child_limits = guard
315 .active_limits
316 .with_max_instructions_per_step(granted_compute)
317 .with_max_session_output_bytes(granted_output);
318 Ok((Self::new(child_limits), epoch))
319 }
320
321 pub fn reclaim_child_task_quota(&self, child: &Self) -> Result<u64> {
327 let (child_remaining, child_executed, child_output, child_interruption) = {
328 let mut child_guard = child
329 .inner
330 .lock()
331 .map_err(|_| anyhow!("Child SharedWasmTaskQuota mutex poisoned"))?;
332 let rem = child_guard.remaining_compute_quota;
333 let exec = child_guard.total_instructions_executed;
334 let out = child_guard.cumulative_output_bytes;
335 let intr = child_guard.last_resource_interruption.clone();
336 child_guard.remaining_compute_quota = 0;
337 (rem, exec, out, intr)
338 };
339 let mut guard = self
340 .inner
341 .lock()
342 .map_err(|_| anyhow!("Parent SharedWasmTaskQuota mutex poisoned"))?;
343 guard.remaining_compute_quota = guard
344 .remaining_compute_quota
345 .saturating_add(child_remaining);
346 guard.total_instructions_executed = guard
347 .total_instructions_executed
348 .saturating_add(child_executed);
349 guard.cumulative_output_bytes = guard
350 .cumulative_output_bytes
351 .saturating_add(child_output);
352 if let Some(intr) = child_interruption {
353 guard.last_resource_interruption = Some(intr);
354 }
355 guard.grant_epoch = guard.grant_epoch.saturating_add(1);
356 Ok(guard.grant_epoch)
357 }
358
359 pub fn snapshot(&self) -> Result<SharedWasmTaskQuotaState> {
364 let guard = self
365 .inner
366 .lock()
367 .map_err(|_| anyhow!("SharedWasmTaskQuota mutex poisoned"))?;
368 Ok(guard.clone())
369 }
370
371 pub(crate) fn with_lock<T>(
372 &self,
373 f: impl FnOnce(&mut SharedWasmTaskQuotaState) -> T,
374 ) -> Result<T> {
375 let mut guard = self
376 .inner
377 .lock()
378 .map_err(|_| anyhow!("SharedWasmTaskQuota mutex poisoned"))?;
379 Ok(f(&mut guard))
380 }
381}
382
383fn push_uleb_u32(mut val: u32, out: &mut Vec<u8>) {
384 loop {
385 #[allow(
386 clippy::expect_used,
387 reason = "Bitmask `val & 0x7F` restricts value to `0..=127`, which always fits in `u8`"
388 )]
389 let mut byte = u8::try_from(val & 0x7F)
390 .expect("7-bit masked u32 always fits in u8");
391 val >>= 7;
392 if val != 0 {
393 byte |= 0x80;
394 }
395 out.push(byte);
396 if val == 0 {
397 break;
398 }
399 }
400}
401
402fn push_sleb_i32(mut val: i32, out: &mut Vec<u8>) {
403 loop {
404 #[allow(
405 clippy::expect_used,
406 reason = "Bitmask `val & 0x7F` restricts value to `0..=127`, which always fits in `u8`"
407 )]
408 let byte = u8::try_from(val & 0x7F)
409 .expect("7-bit masked i32 always fits in u8");
410 val >>= 7;
411 let done = (val == 0 && (byte & 0x40) == 0)
412 || (val == -1 && (byte & 0x40) != 0);
413 if done {
414 out.push(byte);
415 break;
416 }
417 out.push(byte | 0x80);
418 }
419}
420
421fn push_sleb_i64(mut val: i64, out: &mut Vec<u8>) {
422 loop {
423 #[allow(
424 clippy::expect_used,
425 reason = "Bitmask `val & 0x7F` restricts value to `0..=127`, which always fits in `u8`"
426 )]
427 let byte = u8::try_from(val & 0x7F)
428 .expect("7-bit masked i64 always fits in u8");
429 val >>= 7;
430 let done = (val == 0 && (byte & 0x40) == 0)
431 || (val == -1 && (byte & 0x40) != 0);
432 if done {
433 out.push(byte);
434 break;
435 }
436 out.push(byte | 0x80);
437 }
438}
439
440pub(crate) fn read_byte(bytes: &[u8], pos: &mut usize) -> Result<u8> {
441 let b = *bytes
442 .get(*pos)
443 .context("Unexpected EOF while reading WASM binary")?;
444 *pos = pos.saturating_add(1);
445 Ok(b)
446}
447
448pub(crate) fn read_uleb_u32(bytes: &[u8], pos: &mut usize) -> Result<u32> {
449 let mut result = 0u32;
450 let mut shift = 0u32;
451 loop {
452 let byte = read_byte(bytes, pos)?;
453 let low = u32::from(byte & 0x7F);
454 let shifted = low
455 .checked_shl(shift)
456 .context("ULEB128 shift overflow in WASM binary")?;
457 result |= shifted;
458 if (byte & 0x80) == 0 {
459 return Ok(result);
460 }
461 shift = shift.saturating_add(7);
462 ensure!(shift < 35, "Invalid u32 LEB128 encoding in WASM binary");
463 }
464}
465
466pub(crate) fn skip_leb(
467 bytes: &[u8],
468 pos: &mut usize,
469 max_bytes: usize,
470) -> Result<()> {
471 for _ in 0..max_bytes {
472 let b = read_byte(bytes, pos)?;
473 if (b & 0x80) == 0 {
474 return Ok(());
475 }
476 }
477 bail!("Overlong LEB128 immediate in WASM binary")
478}
479
480#[derive(Debug, Clone, Copy, PartialEq, Eq)]
482pub(crate) enum WasmBlockType {
483 Empty,
484 ValType(u8),
485 TypeIdx(u32),
486}
487
488pub(crate) fn read_sleb_i32(bytes: &[u8], pos: &mut usize) -> Result<i32> {
489 let mut result = 0u32;
490 let mut shift = 0u32;
491 for _ in 0..5 {
492 let byte = read_byte(bytes, pos)?;
493 result |= u32::from(byte & 0x7F).wrapping_shl(shift);
494 shift = shift.saturating_add(7);
495 if (byte & 0x80) == 0 {
496 if shift < 32 && (byte & 0x40) != 0 {
497 result |= (!0u32).wrapping_shl(shift);
498 }
499 return Ok(i32::from_le_bytes(result.to_le_bytes()));
500 }
501 }
502 bail!("Overlong s32 LEB128 immediate in WASM binary")
503}
504
505pub(crate) fn read_sleb_i64(bytes: &[u8], pos: &mut usize) -> Result<i64> {
506 let mut result = 0u64;
507 let mut shift = 0u32;
508 for _ in 0..10 {
509 let byte = read_byte(bytes, pos)?;
510 result |= u64::from(byte & 0x7F).wrapping_shl(shift);
511 shift = shift.saturating_add(7);
512 if (byte & 0x80) == 0 {
513 if shift < 64 && (byte & 0x40) != 0 {
514 result |= (!0u64).wrapping_shl(shift);
515 }
516 return Ok(i64::from_le_bytes(result.to_le_bytes()));
517 }
518 }
519 bail!("Overlong s64 LEB128 immediate in WASM binary")
520}
521
522pub(crate) fn read_blocktype(
523 bytes: &[u8],
524 pos: &mut usize,
525) -> Result<WasmBlockType> {
526 let first = *bytes
527 .get(*pos)
528 .context("Unexpected EOF while reading WASM blocktype")?;
529 if first == 0x63 || first == 0x64 {
530 bail!("Typed reference blocktype {first:#04x} is not supported in substitutes");
531 }
532 let mut result = 0u64;
533 let mut shift = 0u32;
534 for _ in 0..5 {
535 let byte = read_byte(bytes, pos)?;
536 result |= u64::from(byte & 0x7F).wrapping_shl(shift);
537 shift = shift.saturating_add(7);
538 if (byte & 0x80) == 0 {
539 if shift < 64 && (byte & 0x40) != 0 {
540 result |= (!0u64).wrapping_shl(shift);
541 }
542 let signed = i64::from_le_bytes(result.to_le_bytes());
543 if signed < 0 {
544 let code = match signed {
545 -64 => return Ok(WasmBlockType::Empty),
546 -1 => 0x7F,
547 -2 => 0x7E,
548 -3 => 0x7D,
549 -4 => 0x7C,
550 -5 => 0x7B,
551 -16 => 0x70,
552 -17 => 0x6F,
553 other => bail!(
554 "Unsupported negative blocktype {other} in WASM binary"
555 ),
556 };
557 return Ok(WasmBlockType::ValType(code));
558 }
559 let idx = u32::try_from(signed)
560 .context("WASM blocktype index exceeds u32 range")?;
561 return Ok(WasmBlockType::TypeIdx(idx));
562 }
563 }
564 bail!("Overlong s33 blocktype immediate in WASM binary")
565}
566
567pub(crate) fn read_memarg(
568 bytes: &[u8],
569 pos: &mut usize,
570) -> Result<(u32, u32)> {
571 let align_flags = read_uleb_u32(bytes, pos)?;
572 let mem_idx = if (align_flags & 0x40) != 0 {
573 read_uleb_u32(bytes, pos)?
574 } else {
575 0
576 };
577 let offset = read_uleb_u32(bytes, pos)?;
578 Ok((mem_idx, offset))
579}
580
581fn skip_blocktype(bytes: &[u8], pos: &mut usize) -> Result<()> {
582 let b = read_byte(bytes, pos)?;
583 if (b & 0x80) != 0 {
584 skip_leb(bytes, pos, 4)?;
586 } else if b == 0x63 || b == 0x64 {
587 skip_leb(bytes, pos, 5)?;
589 }
590 Ok(())
591}
592
593fn skip_memarg(bytes: &[u8], pos: &mut usize) -> Result<()> {
594 let align_flags = read_uleb_u32(bytes, pos)?;
595 if (align_flags & 0x40) != 0 {
596 let _mem_idx = read_uleb_u32(bytes, pos)?;
597 }
598 skip_leb(bytes, pos, 10)
599}
600
601fn push_section(id: u8, payload: &[u8], out: &mut Vec<u8>) -> Result<()> {
602 out.push(id);
603 push_uleb_u32(
604 u32::try_from(payload.len())
605 .context("Instrumented WASM section exceeds u32 max length")?,
606 out,
607 );
608 out.extend_from_slice(payload);
609 Ok(())
610}
611
612fn push_name(name: &str, out: &mut Vec<u8>) -> Result<()> {
613 push_uleb_u32(
614 u32::try_from(name.len())
615 .context("WASM export name exceeds u32 max length")?,
616 out,
617 );
618 out.extend_from_slice(name.as_bytes());
619 Ok(())
620}
621
622pub(crate) fn eval_const_offset(
623 instr: &ConstInstruction,
624 globals: &[Global],
625) -> Option<usize> {
626 match instr {
627 ConstInstruction::I32Const(v) => {
628 usize::try_from(u32::from_le_bytes(v.to_le_bytes())).ok()
629 }
630 ConstInstruction::I64Const(v) => {
631 usize::try_from(u64::from_le_bytes(v.to_le_bytes())).ok()
632 }
633 ConstInstruction::GlobalGet(idx) => {
634 let g_idx = usize::try_from(*idx).ok()?;
635 let g = globals.get(g_idx)?;
636 eval_const_offset(&g.init, globals)
637 }
638 _ => None,
639 }
640}
641
642pub(crate) fn compute_static_data_end(parsed: &TinyWasmModule) -> usize {
643 let mut max_end = 0usize;
644 for seg in &parsed.data {
645 if let DataKind::Active { mem: 0, offset } = &seg.kind
646 && !seg.data.is_empty()
647 && let Some(start) = eval_const_offset(offset, &parsed.globals)
648 {
649 let end = start.saturating_add(seg.data.len());
650 max_end = max_end.max(end);
651 }
652 }
653 max_end
654}
655
656pub const V2_MAX_STRAIGHT_LINE_OPS: u32 = 256;
659
660#[derive(Debug, Clone, Copy)]
661enum V2ControlFrame {
662 BlockOrIf {
663 saved_ops: u32,
664 then_end_ops: Option<u32>,
665 },
666 Loop,
667}
668
669#[derive(Debug, Clone)]
673pub(crate) struct V2CheckpointPlanner {
674 ops_since_checkpoint: u32,
675 stack: Vec<V2ControlFrame>,
676}
677
678impl V2CheckpointPlanner {
679 pub(crate) fn new() -> Self {
680 Self {
681 ops_since_checkpoint: 0,
682 stack: Vec::new(),
683 }
684 }
685
686 pub(crate) fn on_loop_header(&mut self) {
687 self.stack.push(V2ControlFrame::Loop);
688 self.ops_since_checkpoint = 0;
689 }
690
691 pub(crate) fn before_block_or_if(&mut self) -> bool {
692 let emit = self.before_ordinary_op();
693 self.stack.push(V2ControlFrame::BlockOrIf {
694 saved_ops: self.ops_since_checkpoint,
695 then_end_ops: None,
696 });
697 emit
698 }
699
700 pub(crate) fn on_else(&mut self) {
701 if let Some(V2ControlFrame::BlockOrIf {
702 saved_ops,
703 then_end_ops,
704 }) = self.stack.last_mut()
705 {
706 *then_end_ops = Some(self.ops_since_checkpoint);
707 self.ops_since_checkpoint = *saved_ops;
708 }
709 }
710
711 pub(crate) fn on_end(&mut self) {
712 match self.stack.pop() {
713 Some(V2ControlFrame::Loop) => {
714 self.ops_since_checkpoint = 0;
715 }
716 Some(V2ControlFrame::BlockOrIf {
717 saved_ops,
718 then_end_ops,
719 }) => {
720 let alt_ops = if let Some(then_ops) = then_end_ops {
721 then_ops
722 } else {
723 saved_ops
724 };
725 self.ops_since_checkpoint =
726 self.ops_since_checkpoint.max(alt_ops);
727 }
728 None => {}
729 }
730 }
731
732 pub(crate) fn before_bulk_or_grow_op(&mut self) {
733 self.ops_since_checkpoint = 0;
734 }
735
736 pub(crate) fn before_ordinary_op(&mut self) -> bool {
737 if self.ops_since_checkpoint >= V2_MAX_STRAIGHT_LINE_OPS {
738 self.ops_since_checkpoint = 1;
739 true
740 } else {
741 self.ops_since_checkpoint =
742 self.ops_since_checkpoint.saturating_add(1);
743 false
744 }
745 }
746}
747
748#[derive(Clone, Copy)]
749struct QuotaIndices {
750 deduct_func_idx: u32,
751 deduct_1_func_idx: u32,
752 g_quota_rem: u32,
753 g_quota_consumed: u32,
754 g_exhausted: u32,
755 g_interrupted_op: u32,
756 g_required_cost: u32,
757 g_op_ordinal: u32,
758 g_total_mem_pages: u32,
759 g_max_mem_pages: u32,
760 g_phys_max_mem_pages: u32,
761 g_total_table_elems: u32,
762 g_max_table_elems: u32,
763 g_phys_max_table_elems: u32,
764 g_resume_target_op: u32,
765}
766
767fn emit_deduct_1(indices: &QuotaIndices, out: &mut Vec<u8>) {
768 out.push(0x10); push_uleb_u32(indices.deduct_1_func_idx, out);
770}
771
772fn emit_bulk_deduct(
773 scratch_delta_local: u32,
774 indices: &QuotaIndices,
775 out: &mut Vec<u8>,
776) {
777 out.push(0x22); push_uleb_u32(scratch_delta_local, out);
782 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
784 out.push(0xAD); out.push(0x42); push_sleb_i64(1, out);
787 out.push(0x7C); out.push(0x10); push_uleb_u32(indices.deduct_func_idx, out);
790}
791
792fn emit_memory_grow_sequence(
793 mem_idx: u32,
794 declared_max_pages: i64,
795 scratch_delta_local: u32,
796 scratch_res_local: u32,
797 indices: &QuotaIndices,
798 out: &mut Vec<u8>,
799) {
800 out.push(0x21); push_uleb_u32(scratch_delta_local, out);
803
804 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
807 out.push(0x41); push_sleb_i32(0, out);
809 out.push(0x48); out.push(0x23); push_uleb_u32(indices.g_total_mem_pages, out);
814 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
816 out.push(0xAD); out.push(0x7C); out.push(0x23); push_uleb_u32(indices.g_max_mem_pages, out);
820 out.push(0x56); out.push(0x3F); push_uleb_u32(mem_idx, out);
825 out.push(0xAD); out.push(0x20); push_uleb_u32(scratch_delta_local, out);
828 out.push(0xAD); out.push(0x7C); out.push(0x42); push_sleb_i64(declared_max_pages, out);
832 out.push(0x56); out.push(0x72); out.push(0x72); out.push(0x04);
839 out.push(VALTYPE_I32);
840 emit_deduct_1(indices, out);
842 out.push(0x41); push_sleb_i32(-1, out);
844 out.push(0x05); out.push(0x20); push_uleb_u32(scratch_delta_local, out);
848 out.push(0xAD); out.push(0x42); push_sleb_i64(64, out);
851 out.push(0x7E); out.push(0x42); push_sleb_i64(1, out);
854 out.push(0x7C); out.push(0x10); push_uleb_u32(indices.deduct_func_idx, out);
857
858 out.push(0x23); push_uleb_u32(indices.g_total_mem_pages, out);
861 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
863 out.push(0xAD); out.push(0x7C); out.push(0x23); push_uleb_u32(indices.g_phys_max_mem_pages, out);
867 out.push(0x56); out.push(0x04); out.push(0x40);
870 out.push(0x41); push_sleb_i32(2, out);
872 out.push(0x24); push_uleb_u32(indices.g_exhausted, out);
874 out.push(0x23); push_uleb_u32(indices.g_total_mem_pages, out);
876 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
878 out.push(0xAD); out.push(0x7C); out.push(0x24); push_uleb_u32(indices.g_interrupted_op, out);
882 out.push(0x00); out.push(0x0B); out.push(0x20); push_uleb_u32(scratch_delta_local, out);
888 out.push(0x40); push_uleb_u32(mem_idx, out);
890 out.push(0x22); push_uleb_u32(scratch_res_local, out);
892 out.push(0x41); push_sleb_i32(0, out);
894 out.push(0x48); out.push(0x04); out.push(0x40);
897 out.push(0x41); push_sleb_i32(2, out);
899 out.push(0x24); push_uleb_u32(indices.g_exhausted, out);
901 out.push(0x23); push_uleb_u32(indices.g_total_mem_pages, out);
903 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
905 out.push(0xAD); out.push(0x7C); out.push(0x24); push_uleb_u32(indices.g_interrupted_op, out);
909 out.push(0x00); out.push(0x0B); out.push(0x23); push_uleb_u32(indices.g_total_mem_pages, out);
915 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
917 out.push(0xAD); out.push(0x7C); out.push(0x24); push_uleb_u32(indices.g_total_mem_pages, out);
921 out.push(0x20); push_uleb_u32(scratch_res_local, out);
923 out.push(0x0B); }
925
926fn emit_table_grow_sequence(
927 table_idx: u32,
928 declared_max_elems: i64,
929 scratch_delta_local: u32,
930 scratch_res_local: u32,
931 indices: &QuotaIndices,
932 out: &mut Vec<u8>,
933) {
934 out.push(0x21); push_uleb_u32(scratch_delta_local, out);
938
939 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
942 out.push(0x41); push_sleb_i32(0, out);
944 out.push(0x48); out.push(0x23); push_uleb_u32(indices.g_total_table_elems, out);
949 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
951 out.push(0xAD); out.push(0x7C); out.push(0x23); push_uleb_u32(indices.g_max_table_elems, out);
955 out.push(0x56); out.push(0xFC); push_uleb_u32(16, out);
960 push_uleb_u32(table_idx, out);
961 out.push(0xAD); out.push(0x20); push_uleb_u32(scratch_delta_local, out);
964 out.push(0xAD); out.push(0x7C); out.push(0x42); push_sleb_i64(declared_max_elems, out);
968 out.push(0x56); out.push(0x72); out.push(0x72); out.push(0x04);
975 out.push(VALTYPE_I32);
976 emit_deduct_1(indices, out);
978 out.push(0x41); push_sleb_i32(-1, out);
980 out.push(0x21); push_uleb_u32(scratch_delta_local, out);
982 out.push(0x41); push_sleb_i32(TABLE_GROW_DENIAL_SENTINEL_DELTA, out);
984 out.push(0x05); out.push(0x20); push_uleb_u32(scratch_delta_local, out);
988 out.push(0xAD); out.push(0x42); push_sleb_i64(1, out);
991 out.push(0x7C); out.push(0x10); push_uleb_u32(indices.deduct_func_idx, out);
994
995 out.push(0x23); push_uleb_u32(indices.g_total_table_elems, out);
998 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
1000 out.push(0xAD); out.push(0x7C); out.push(0x23); push_uleb_u32(indices.g_phys_max_table_elems, out);
1004 out.push(0x56); out.push(0x04); out.push(0x40);
1007 out.push(0x41); push_sleb_i32(3, out);
1009 out.push(0x24); push_uleb_u32(indices.g_exhausted, out);
1011 out.push(0x23); push_uleb_u32(indices.g_total_table_elems, out);
1013 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
1015 out.push(0xAD); out.push(0x7C); out.push(0x24); push_uleb_u32(indices.g_interrupted_op, out);
1019 out.push(0x00); out.push(0x0B); out.push(0x20); push_uleb_u32(scratch_delta_local, out);
1024 out.push(0x0B); out.push(0xFC);
1029 push_uleb_u32(15, out);
1030 push_uleb_u32(table_idx, out);
1031 out.push(0x22); push_uleb_u32(scratch_res_local, out);
1033
1034 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
1037 out.push(0x41); push_sleb_i32(0, out);
1039 out.push(0x4E); out.push(0x04); out.push(0x40);
1042 out.push(0x20); push_uleb_u32(scratch_res_local, out);
1045 out.push(0x41); push_sleb_i32(0, out);
1047 out.push(0x48); out.push(0x04); out.push(0x40);
1050 out.push(0x41); push_sleb_i32(3, out);
1052 out.push(0x24); push_uleb_u32(indices.g_exhausted, out);
1054 out.push(0x23); push_uleb_u32(indices.g_total_table_elems, out);
1056 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
1058 out.push(0xAD); out.push(0x7C); out.push(0x24); push_uleb_u32(indices.g_interrupted_op, out);
1062 out.push(0x00); out.push(0x0B); out.push(0x23); push_uleb_u32(indices.g_total_table_elems, out);
1068 out.push(0x20); push_uleb_u32(scratch_delta_local, out);
1070 out.push(0xAD); out.push(0x7C); out.push(0x24); push_uleb_u32(indices.g_total_table_elems, out);
1074 out.push(0x0B); }
1076
1077#[allow(
1078 clippy::too_many_lines,
1079 reason = "Single-pass WebAssembly bytecode instruction scanner and quota instrumenter"
1080)]
1081fn instrument_function_body(
1082 body_bytes: &[u8],
1083 num_params: u32,
1084 mem_declared_max: &[i64],
1085 table_declared_max: &[i64],
1086 indices: &QuotaIndices,
1087) -> Result<Vec<u8>> {
1088 let mut pos = 0usize;
1089 let num_local_runs = read_uleb_u32(body_bytes, &mut pos)?;
1090 let mut local_runs: Vec<(u32, u8)> =
1091 Vec::with_capacity(usize::try_from(num_local_runs)?.saturating_add(1));
1092 let mut total_locals = num_params;
1093 for _ in 0..num_local_runs {
1094 let count = read_uleb_u32(body_bytes, &mut pos)?;
1095 let vt = read_byte(body_bytes, &mut pos)?;
1096 total_locals = total_locals
1097 .checked_add(count)
1098 .context("WASM function local count overflow")?;
1099 local_runs.push((count, vt));
1100 }
1101 let scratch_delta_local = total_locals;
1102 let scratch_res_local = total_locals
1103 .checked_add(1)
1104 .context("WASM scratch local index overflow")?;
1105 local_runs.push((2, VALTYPE_I32));
1106
1107 let mut out = Vec::with_capacity(body_bytes.len().saturating_mul(3));
1108 push_uleb_u32(u32::try_from(local_runs.len())?, &mut out);
1109 for (count, vt) in local_runs {
1110 push_uleb_u32(count, &mut out);
1111 out.push(vt);
1112 }
1113
1114 emit_deduct_1(indices, &mut out);
1116 let mut planner = V2CheckpointPlanner::new();
1117
1118 while pos < body_bytes.len() {
1119 let instr_start = pos;
1120 let opcode = read_byte(body_bytes, &mut pos)?;
1121
1122 if opcode == 0x0B && pos == body_bytes.len() {
1124 out.push(0x0B);
1125 break;
1126 }
1127
1128 if opcode == 0x05 {
1130 planner.on_else();
1131 out.push(0x05);
1132 continue;
1133 }
1134
1135 if opcode == 0x0B {
1137 planner.on_end();
1138 out.push(0x0B);
1139 continue;
1140 }
1141
1142 if opcode == 0x03 {
1144 skip_blocktype(body_bytes, &mut pos)?;
1145 if let Some(slice) = body_bytes.get(instr_start..pos) {
1146 out.extend_from_slice(slice);
1147 }
1148 planner.on_loop_header();
1149 emit_deduct_1(indices, &mut out);
1150 continue;
1151 }
1152
1153 if opcode == 0x02 || opcode == 0x04 {
1155 skip_blocktype(body_bytes, &mut pos)?;
1156 if planner.before_block_or_if() {
1157 emit_deduct_1(indices, &mut out);
1158 }
1159 if let Some(slice) = body_bytes.get(instr_start..pos) {
1160 out.extend_from_slice(slice);
1161 }
1162 continue;
1163 }
1164
1165 if opcode == 0x40 {
1167 planner.before_bulk_or_grow_op();
1168 let mem_idx = read_uleb_u32(body_bytes, &mut pos)?;
1169 let declared_max = *mem_declared_max
1170 .get(usize::try_from(mem_idx)?)
1171 .context(
1172 "WASM memory.grow references out-of-bounds memory index",
1173 )?;
1174 emit_memory_grow_sequence(
1175 mem_idx,
1176 declared_max,
1177 scratch_delta_local,
1178 scratch_res_local,
1179 indices,
1180 &mut out,
1181 );
1182 continue;
1183 }
1184
1185 if opcode == 0xFC {
1187 let subop = read_uleb_u32(body_bytes, &mut pos)?;
1188 match subop {
1189 0..=7 => {
1190 if planner.before_ordinary_op() {
1191 emit_deduct_1(indices, &mut out);
1192 }
1193 if let Some(slice) = body_bytes.get(instr_start..pos) {
1194 out.extend_from_slice(slice);
1195 }
1196 }
1197 8 | 10 | 12 | 14 => {
1198 planner.before_bulk_or_grow_op();
1200 let _idx1 = read_uleb_u32(body_bytes, &mut pos)?;
1201 let _idx2 = read_uleb_u32(body_bytes, &mut pos)?;
1202 emit_bulk_deduct(scratch_delta_local, indices, &mut out);
1203 if let Some(slice) = body_bytes.get(instr_start..pos) {
1204 out.extend_from_slice(slice);
1205 }
1206 }
1207 11 | 17 => {
1208 planner.before_bulk_or_grow_op();
1210 let _idx = read_uleb_u32(body_bytes, &mut pos)?;
1211 emit_bulk_deduct(scratch_delta_local, indices, &mut out);
1212 if let Some(slice) = body_bytes.get(instr_start..pos) {
1213 out.extend_from_slice(slice);
1214 }
1215 }
1216 16 | 9 | 13 => {
1217 let _idx = read_uleb_u32(body_bytes, &mut pos)?;
1219 if planner.before_ordinary_op() {
1220 emit_deduct_1(indices, &mut out);
1221 }
1222 if let Some(slice) = body_bytes.get(instr_start..pos) {
1223 out.extend_from_slice(slice);
1224 }
1225 }
1226 15 => {
1227 planner.before_bulk_or_grow_op();
1229 let table_idx = read_uleb_u32(body_bytes, &mut pos)?;
1230 let declared_max = *table_declared_max
1231 .get(usize::try_from(table_idx)?)
1232 .context("WASM table.grow references out-of-bounds table index")?;
1233 emit_table_grow_sequence(
1234 table_idx,
1235 declared_max,
1236 scratch_delta_local,
1237 scratch_res_local,
1238 indices,
1239 &mut out,
1240 );
1241 }
1242 other => {
1243 bail!("Unsupported 0xFC subopcode {other} in WASM module")
1244 }
1245 }
1246 continue;
1247 }
1248
1249 if opcode == 0xFB {
1251 let subop = read_uleb_u32(body_bytes, &mut pos)?;
1252 BootstrapKernelVersion::V1
1253 .ensure_wasm_opcode_supported(Some(0xFB), subop)?;
1254 }
1255
1256 if opcode == 0xFD {
1258 let subop = read_uleb_u32(body_bytes, &mut pos)?;
1259 BootstrapKernelVersion::V1
1260 .ensure_wasm_opcode_supported(Some(0xFD), subop)?;
1261 match subop {
1262 0..=11 | 92..=93 => {
1263 skip_memarg(body_bytes, &mut pos)?;
1264 }
1265 12 | 13 => {
1266 pos = pos.saturating_add(16);
1267 ensure!(
1268 pos <= body_bytes.len(),
1269 "Truncated 16-byte SIMD immediate in WASM module"
1270 );
1271 }
1272 21..=34 => {
1273 let _lane = read_byte(body_bytes, &mut pos)?;
1274 }
1275 84..=91 => {
1276 skip_memarg(body_bytes, &mut pos)?;
1277 let _lane = read_byte(body_bytes, &mut pos)?;
1278 }
1279 _ => {}
1280 }
1281 if planner.before_ordinary_op() {
1282 emit_deduct_1(indices, &mut out);
1283 }
1284 if let Some(slice) = body_bytes.get(instr_start..pos) {
1285 out.extend_from_slice(slice);
1286 }
1287 continue;
1288 }
1289
1290 BootstrapKernelVersion::V1
1291 .ensure_wasm_opcode_supported(None, u32::from(opcode))?;
1292
1293 match opcode {
1295 0x00 | 0x01 | 0x0F | 0x1A | 0x1B | 0xD1 | 0xD3 | 0xD4 => {}
1296 0x0C | 0x0D | 0x10 | 0x12 | 0x14 | 0x15 | 0x20..=0x26 | 0x3F
1297 | 0xD2 | 0xD5 | 0xD6 => {
1298 let _idx = read_uleb_u32(body_bytes, &mut pos)?;
1299 }
1300 0x11 | 0x13 => {
1301 let _type_idx = read_uleb_u32(body_bytes, &mut pos)?;
1302 let _table_idx = read_uleb_u32(body_bytes, &mut pos)?;
1303 }
1304 0x0E => {
1305 let count = read_uleb_u32(body_bytes, &mut pos)?;
1306 for _ in 0..count {
1307 let _lbl = read_uleb_u32(body_bytes, &mut pos)?;
1308 }
1309 let _default_lbl = read_uleb_u32(body_bytes, &mut pos)?;
1310 }
1311 0x1C => {
1312 let count = read_uleb_u32(body_bytes, &mut pos)?;
1313 for _ in 0..count {
1314 skip_blocktype(body_bytes, &mut pos)?;
1315 }
1316 }
1317 0x28..=0x3E => {
1318 skip_memarg(body_bytes, &mut pos)?;
1319 }
1320 0x41 => {
1321 skip_leb(body_bytes, &mut pos, 5)?;
1322 }
1323 0x42 => {
1324 skip_leb(body_bytes, &mut pos, 10)?;
1325 }
1326 0x43 => {
1327 pos = pos.saturating_add(4);
1328 ensure!(
1329 pos <= body_bytes.len(),
1330 "Truncated f32.const immediate in WASM module"
1331 );
1332 }
1333 0x44 => {
1334 pos = pos.saturating_add(8);
1335 ensure!(
1336 pos <= body_bytes.len(),
1337 "Truncated f64.const immediate in WASM module"
1338 );
1339 }
1340 0x45..=0xC4 => {}
1341 0xD0 => {
1342 skip_leb(body_bytes, &mut pos, 5)?;
1343 }
1344 other => {
1345 bail!("Unsupported WASM opcode {other:#04x} during quota instrumentation");
1346 }
1347 }
1348
1349 if planner.before_ordinary_op() {
1350 emit_deduct_1(indices, &mut out);
1351 }
1352 if let Some(slice) = body_bytes.get(instr_start..pos) {
1353 out.extend_from_slice(slice);
1354 }
1355 }
1356
1357 Ok(out)
1358}
1359
1360fn encode_deduct_helper_body(indices: &QuotaIndices) -> Vec<u8> {
1361 let mut body = Vec::with_capacity(96);
1362 body.push(0x00); body.push(0x23); push_uleb_u32(indices.g_op_ordinal, &mut body);
1367 body.push(0x42); push_sleb_i64(1, &mut body);
1369 body.push(0x7C); body.push(0x24); push_uleb_u32(indices.g_op_ordinal, &mut body);
1372
1373 body.push(0x23); push_uleb_u32(indices.g_op_ordinal, &mut body);
1378 body.push(0x23); push_uleb_u32(indices.g_resume_target_op, &mut body);
1380 body.push(0x54); body.push(0x04); body.push(0x40);
1383 body.push(0x0F); body.push(0x0B); body.push(0x03); body.push(0x40);
1389 body.push(0x23); push_uleb_u32(indices.g_quota_rem, &mut body);
1392 body.push(0x20); push_uleb_u32(0, &mut body);
1394 body.push(0x54); body.push(0x04); body.push(0x40);
1397 body.push(0x41); push_sleb_i32(1, &mut body);
1399 body.push(0x24); push_uleb_u32(indices.g_exhausted, &mut body);
1401 body.push(0x23); push_uleb_u32(indices.g_op_ordinal, &mut body);
1403 body.push(0x24); push_uleb_u32(indices.g_interrupted_op, &mut body);
1405 body.push(0x20); push_uleb_u32(0, &mut body);
1407 body.push(0x24); push_uleb_u32(indices.g_required_cost, &mut body);
1409 body.push(0x00); body.push(0x0C); push_uleb_u32(1, &mut body);
1412 body.push(0x0B); body.push(0x0B); body.push(0x23); push_uleb_u32(indices.g_quota_rem, &mut body);
1418 body.push(0x20); push_uleb_u32(0, &mut body);
1420 body.push(0x7D); body.push(0x24); push_uleb_u32(indices.g_quota_rem, &mut body);
1423
1424 body.push(0x23); push_uleb_u32(indices.g_quota_consumed, &mut body);
1427 body.push(0x20); push_uleb_u32(0, &mut body);
1429 body.push(0x7C); body.push(0x24); push_uleb_u32(indices.g_quota_consumed, &mut body);
1432
1433 body.push(0x0B); body
1435}
1436
1437fn encode_deduct_1_helper_body(indices: &QuotaIndices) -> Vec<u8> {
1441 let mut body = Vec::with_capacity(88);
1442 body.push(0x00); body.push(0x23); push_uleb_u32(indices.g_op_ordinal, &mut body);
1447 body.push(0x42); push_sleb_i64(1, &mut body);
1449 body.push(0x7C); body.push(0x24); push_uleb_u32(indices.g_op_ordinal, &mut body);
1452
1453 body.push(0x23); push_uleb_u32(indices.g_op_ordinal, &mut body);
1456 body.push(0x23); push_uleb_u32(indices.g_resume_target_op, &mut body);
1458 body.push(0x54); body.push(0x04); body.push(0x40);
1461 body.push(0x0F); body.push(0x0B); body.push(0x03); body.push(0x40);
1467 body.push(0x23); push_uleb_u32(indices.g_quota_rem, &mut body);
1470 body.push(0x50); body.push(0x04); body.push(0x40);
1473 body.push(0x41); push_sleb_i32(1, &mut body);
1475 body.push(0x24); push_uleb_u32(indices.g_exhausted, &mut body);
1477 body.push(0x23); push_uleb_u32(indices.g_op_ordinal, &mut body);
1479 body.push(0x24); push_uleb_u32(indices.g_interrupted_op, &mut body);
1481 body.push(0x42); push_sleb_i64(1, &mut body);
1483 body.push(0x24); push_uleb_u32(indices.g_required_cost, &mut body);
1485 body.push(0x00); body.push(0x0C); push_uleb_u32(1, &mut body);
1488 body.push(0x0B); body.push(0x0B); body.push(0x23); push_uleb_u32(indices.g_quota_rem, &mut body);
1494 body.push(0x42); push_sleb_i64(1, &mut body);
1496 body.push(0x7D); body.push(0x24); push_uleb_u32(indices.g_quota_rem, &mut body);
1499
1500 body.push(0x23); push_uleb_u32(indices.g_quota_consumed, &mut body);
1503 body.push(0x42); push_sleb_i64(1, &mut body);
1505 body.push(0x7C); body.push(0x24); push_uleb_u32(indices.g_quota_consumed, &mut body);
1508
1509 body.push(0x0B); body
1511}
1512
1513fn patch_deduct_suspension_call(
1514 funcs: &mut [ctb_formats_dcdata::tinywasm::types::WasmFunction],
1515 func_idx: u32,
1516 host_suspend_func_idx: u32,
1517 label: &str,
1518) -> Result<()> {
1519 let def = funcs
1520 .get_mut(usize::try_from(func_idx)?)
1521 .with_context(|| {
1522 format!("Missing {label} function in parsed instrumented module")
1523 })?;
1524 let mut instrs = def.instructions.clone().into_vec();
1525 let mut patched = false;
1526 for instr in &mut instrs {
1527 if matches!(instr, Instruction::Unreachable) {
1528 *instr = Instruction::Call(host_suspend_func_idx);
1529 patched = true;
1530 break;
1531 }
1532 }
1533 ensure!(patched, "Failed to locate suspension point in {label}");
1534 def.instructions = instrs.into_boxed_slice();
1535 Ok(())
1536}
1537
1538fn build_suspendable_tinywasm_module(
1539 parsed_instrumented: &TinyWasmModule,
1540 deduct_func_idx: u32,
1541 deduct_1_func_idx: u32,
1542) -> Result<TinyWasmModule> {
1543 let mut module = parsed_instrumented.clone();
1544 let mut func_types = module.func_types.into_vec();
1545 let suspend_type_idx = u32::try_from(func_types.len())?;
1546 func_types.push(FuncType {
1547 params: Box::new([]),
1548 results: Box::new([]),
1549 });
1550 module.func_types = func_types.into_boxed_slice();
1551
1552 let host_suspend_func_idx = 0u32;
1553 let host_capability_func_idx = 1u32;
1554 let import_shift = 2u32;
1555 let mut imports = module.imports.into_vec();
1556 imports.push(Import {
1557 module: Box::from(CTB_HOST_IMPORT_MODULE),
1558 name: Box::from(CTB_HOST_SUSPEND_IMPORT_NAME),
1559 kind: ImportKind::Function(suspend_type_idx),
1560 });
1561 imports.push(Import {
1562 module: Box::from(CTB_HOST_IMPORT_MODULE),
1563 name: Box::from(CTB_HOST_CAPABILITY_IMPORT_NAME),
1564 kind: ImportKind::Function(suspend_type_idx),
1565 });
1566 module.imports = imports.into_boxed_slice();
1567
1568 if let Some(start) = &mut module.start_func {
1569 *start = start.saturating_add(import_shift);
1570 }
1571 let mut exports = module.exports.into_vec();
1572 let mut capability_yield_def_idx: Option<u32> = None;
1573 for exp in &mut exports {
1574 if exp.name.as_ref() == CTB_CAPABILITY_YIELD_EXPORT {
1575 ensure!(
1576 exp.kind == ExternalKind::Func,
1577 "Reserved export '{}' must be a function",
1578 CTB_CAPABILITY_YIELD_EXPORT
1579 );
1580 capability_yield_def_idx = Some(exp.index);
1581 }
1582 if exp.kind == ExternalKind::Func {
1583 exp.index = exp.index.saturating_add(import_shift);
1584 }
1585 }
1586 module.exports = exports.into_boxed_slice();
1587
1588 let mut globals = module.globals.into_vec();
1589 for glob in &mut globals {
1590 if let ConstInstruction::RefFunc(idx) = &mut glob.init {
1591 *idx = idx.saturating_add(import_shift);
1592 }
1593 }
1594 module.globals = globals.into_boxed_slice();
1595
1596 let mut elements = module.elements.into_vec();
1597 for elem in &mut elements {
1598 let mut items = elem.items.clone().into_vec();
1599 for item in &mut items {
1600 match item {
1601 ElementItem::Func(idx)
1602 | ElementItem::Expr(ConstInstruction::RefFunc(idx)) => {
1603 *idx = idx.saturating_add(import_shift);
1604 }
1605 _ => {}
1606 }
1607 }
1608 elem.items = items.into_boxed_slice();
1609 }
1610 module.elements = elements.into_boxed_slice();
1611
1612 let mut funcs = module.funcs.into_vec();
1613 for func in &mut funcs {
1614 let mut instrs = func.instructions.clone().into_vec();
1615 for instr in &mut instrs {
1616 match instr {
1617 Instruction::Call(idx)
1618 | Instruction::ReturnCall(idx)
1619 | Instruction::RefFunc(idx) => {
1620 *idx = idx.saturating_add(import_shift);
1621 }
1622 _ => {}
1623 }
1624 }
1625 func.instructions = instrs.into_boxed_slice();
1626 }
1627
1628 patch_deduct_suspension_call(
1629 &mut funcs,
1630 deduct_func_idx,
1631 host_suspend_func_idx,
1632 "$__ctb_deduct",
1633 )?;
1634 patch_deduct_suspension_call(
1635 &mut funcs,
1636 deduct_1_func_idx,
1637 host_suspend_func_idx,
1638 "$__ctb_deduct_1",
1639 )?;
1640
1641 if let Some(y_idx) = capability_yield_def_idx {
1642 let yield_def = funcs.get_mut(usize::try_from(y_idx)?).context(
1643 "Missing $__ctb_capability_yield function in parsed instrumented module",
1644 )?;
1645 ensure!(
1646 yield_def.ty.params.is_empty() && yield_def.ty.results.is_empty(),
1647 "Reserved export '{}' must have WebAssembly signature () -> ()",
1648 CTB_CAPABILITY_YIELD_EXPORT
1649 );
1650 yield_def.instructions =
1651 Box::new([Instruction::Call(host_capability_func_idx), Instruction::Return]);
1652 }
1653 module.funcs = funcs.into_boxed_slice();
1654
1655 Ok(module)
1656}
1657
1658fn precheck_code_section_kernel_v1_opcodes(wasm_bytes: &[u8]) -> Result<()> {
1659 if wasm_bytes.get(0..8) != Some(WASM_HEADER.as_slice()) {
1660 return Ok(());
1661 }
1662 let mut pos = 8usize;
1663 let dummy_indices = QuotaIndices {
1664 deduct_func_idx: 0,
1665 deduct_1_func_idx: 0,
1666 g_quota_rem: 0,
1667 g_quota_consumed: 0,
1668 g_exhausted: 0,
1669 g_interrupted_op: 0,
1670 g_required_cost: 0,
1671 g_op_ordinal: 0,
1672 g_total_mem_pages: 0,
1673 g_max_mem_pages: 0,
1674 g_phys_max_mem_pages: 0,
1675 g_total_table_elems: 0,
1676 g_max_table_elems: 0,
1677 g_phys_max_table_elems: 0,
1678 g_resume_target_op: 0,
1679 };
1680 while pos < wasm_bytes.len() {
1681 let Ok(sec_id) = read_byte(wasm_bytes, &mut pos) else {
1682 return Ok(());
1683 };
1684 let Ok(sec_len_u32) = read_uleb_u32(wasm_bytes, &mut pos) else {
1685 return Ok(());
1686 };
1687 let Ok(sec_len) = usize::try_from(sec_len_u32) else {
1688 return Ok(());
1689 };
1690 let Some(sec_end) = pos.checked_add(sec_len) else {
1691 return Ok(());
1692 };
1693 let Some(payload) = wasm_bytes.get(pos..sec_end) else {
1694 return Ok(());
1695 };
1696 pos = sec_end;
1697 if sec_id == SEC_CODE {
1698 let mut p = 0usize;
1699 let Ok(count) = read_uleb_u32(payload, &mut p) else {
1700 return Ok(());
1701 };
1702 for _ in 0..count {
1703 let Ok(body_len_u32) = read_uleb_u32(payload, &mut p) else {
1704 return Ok(());
1705 };
1706 let Ok(body_len) = usize::try_from(body_len_u32) else {
1707 return Ok(());
1708 };
1709 let Some(body_end) = p.checked_add(body_len) else {
1710 return Ok(());
1711 };
1712 let Some(body_slice) = payload.get(p..body_end) else {
1713 return Ok(());
1714 };
1715 p = body_end;
1716 let _ = instrument_function_body(
1717 body_slice,
1718 0,
1719 &[65_536],
1720 &[10_000_000],
1721 &dummy_indices,
1722 )?;
1723 }
1724 }
1725 }
1726 Ok(())
1727}
1728
1729#[allow(
1738 clippy::too_many_lines,
1739 reason = "Complete binary WebAssembly section parser and instrumenter"
1740)]
1741pub fn instrument_wasm_module_bytes(
1742 wasm_bytes: &[u8],
1743) -> Result<InstrumentedWasmModule> {
1744 let parsed_uninstrumented = match ctb_formats_dcdata::tinywasm::parser::Parser::new()
1745 .parse_module_bytes(wasm_bytes)
1746 {
1747 Ok(module) => module,
1748 Err(error) => {
1749 precheck_code_section_kernel_v1_opcodes(wasm_bytes)?;
1750 bail!("Failed to parse WebAssembly module in tinywasm: {error:?}");
1751 }
1752 };
1753 ensure!(
1754 parsed_uninstrumented.imports.is_empty(),
1755 "WebAssembly host imports are not supported"
1756 );
1757 ensure!(
1758 parsed_uninstrumented
1759 .memory_types
1760 .iter()
1761 .all(|memory| memory.arch == MemoryArch::I32),
1762 "WebAssembly memory64 is not supported"
1763 );
1764 ensure!(
1765 parsed_uninstrumented.exports.iter().all(|exp| {
1766 !exp.name.starts_with("__ctb_")
1767 || exp.name.as_ref() == CTB_CAPABILITY_YIELD_EXPORT
1768 }),
1769 "WebAssembly module must not declare reserved '__ctb_*' exports"
1770 );
1771 if let Some(cap_exp) = parsed_uninstrumented
1772 .exports
1773 .iter()
1774 .find(|exp| exp.name.as_ref() == CTB_CAPABILITY_YIELD_EXPORT)
1775 {
1776 ensure!(
1777 cap_exp.kind == ExternalKind::Func,
1778 "Reserved export '{}' must be a function",
1779 CTB_CAPABILITY_YIELD_EXPORT
1780 );
1781 let cap_fn = parsed_uninstrumented
1782 .funcs
1783 .get(usize::try_from(cap_exp.index)?)
1784 .context("Reserved capability yield export index out of bounds")?;
1785 ensure!(
1786 cap_fn.ty.params.is_empty() && cap_fn.ty.results.is_empty(),
1787 "Reserved export '{}' must have WebAssembly signature () -> ()",
1788 CTB_CAPABILITY_YIELD_EXPORT
1789 );
1790 }
1791
1792 let initial_memory_pages = parsed_uninstrumented
1793 .memory_types
1794 .iter()
1795 .try_fold(0usize, |total: usize, memory| -> Result<usize> {
1796 total
1797 .checked_add(usize::try_from(memory.page_count_initial)?)
1798 .context("Initial WASM memory page count overflow")
1799 })?;
1800 let initial_table_elements = parsed_uninstrumented
1801 .table_types
1802 .iter()
1803 .try_fold(0usize, |total: usize, table| -> Result<usize> {
1804 total
1805 .checked_add(usize::try_from(table.size_initial)?)
1806 .context("Initial WASM table element count overflow")
1807 })?;
1808 let static_data_end = compute_static_data_end(&parsed_uninstrumented);
1809 let num_guest_globals = parsed_uninstrumented.globals.len();
1810 let num_memories = parsed_uninstrumented.memory_types.len();
1811 let num_tables = parsed_uninstrumented.table_types.len();
1812
1813 let mem_declared_max: Vec<i64> = parsed_uninstrumented
1814 .memory_types
1815 .iter()
1816 .map(|m| -> Result<i64> {
1817 let max_pages = m.page_count_max.unwrap_or(65_536);
1820 Ok(i64::try_from(max_pages)?)
1821 })
1822 .collect::<Result<Vec<i64>>>()?;
1823 let table_declared_max: Vec<i64> = parsed_uninstrumented
1824 .table_types
1825 .iter()
1826 .map(|t| {
1827 let clamped = t
1831 .size_max
1832 .unwrap_or(MAX_CLAMPED_DECLARED_TABLE_ELEMENTS)
1833 .min(MAX_CLAMPED_DECLARED_TABLE_ELEMENTS.max(t.size_initial));
1834 i64::from(clamped)
1835 })
1836 .collect();
1837
1838 ensure!(
1839 wasm_bytes.get(0..8) == Some(WASM_HEADER.as_slice()),
1840 "Invalid WebAssembly binary magic/version header"
1841 );
1842 let mut pos = 8usize;
1843 let mut sec_type: Option<&[u8]> = None;
1844 let mut sec_import: Option<&[u8]> = None;
1845 let mut sec_func: Option<&[u8]> = None;
1846 let mut sec_table: Option<&[u8]> = None;
1847 let mut sec_memory: Option<&[u8]> = None;
1848 let mut sec_global: Option<&[u8]> = None;
1849 let mut sec_export: Option<&[u8]> = None;
1850 let mut sec_start: Option<&[u8]> = None;
1851 let mut sec_element: Option<&[u8]> = None;
1852 let mut sec_datacount: Option<&[u8]> = None;
1853 let mut sec_code: Option<&[u8]> = None;
1854 let mut sec_data: Option<&[u8]> = None;
1855
1856 while pos < wasm_bytes.len() {
1857 let sec_id = read_byte(wasm_bytes, &mut pos)?;
1858 let sec_len = usize::try_from(read_uleb_u32(wasm_bytes, &mut pos)?)?;
1859 let sec_end = pos
1860 .checked_add(sec_len)
1861 .context("WASM section length overflow")?;
1862 let payload = wasm_bytes
1863 .get(pos..sec_end)
1864 .context("Truncated WASM section payload")?;
1865 pos = sec_end;
1866 match sec_id {
1867 SEC_CUSTOM => {}
1868 SEC_TYPE => sec_type = Some(payload),
1869 SEC_IMPORT => sec_import = Some(payload),
1870 SEC_FUNCTION => sec_func = Some(payload),
1871 SEC_TABLE => sec_table = Some(payload),
1872 SEC_MEMORY => sec_memory = Some(payload),
1873 SEC_GLOBAL => sec_global = Some(payload),
1874 SEC_EXPORT => sec_export = Some(payload),
1875 SEC_START => sec_start = Some(payload),
1876 SEC_ELEMENT => sec_element = Some(payload),
1877 SEC_DATA_COUNT => sec_datacount = Some(payload),
1878 SEC_CODE => sec_code = Some(payload),
1879 SEC_DATA => sec_data = Some(payload),
1880 other => bail!("Unsupported WASM section id {other}"),
1881 }
1882 }
1883
1884 let (num_guest_types, raw_types_tail) = if let Some(payload) = sec_type {
1886 let mut p = 0usize;
1887 let count = read_uleb_u32(payload, &mut p)?;
1888 let tail = payload
1889 .get(p..)
1890 .context("Truncated WASM Type section payload")?;
1891 (count, tail)
1892 } else {
1893 (0u32, &[][..])
1894 };
1895 let deduct_type_idx = num_guest_types;
1896 let deduct_1_type_idx = num_guest_types.saturating_add(1);
1897
1898 let mut guest_func_type_indices: Vec<u32> = Vec::new();
1900 let raw_funcs_tail = if let Some(payload) = sec_func {
1901 let mut p = 0usize;
1902 let count = read_uleb_u32(payload, &mut p)?;
1903 let tail_start = p;
1904 for _ in 0..count {
1905 guest_func_type_indices.push(read_uleb_u32(payload, &mut p)?);
1906 }
1907 payload
1908 .get(tail_start..)
1909 .context("Truncated WASM Function section payload")?
1910 } else {
1911 &[][..]
1912 };
1913 let num_guest_funcs = u32::try_from(guest_func_type_indices.len())?;
1914 let deduct_func_idx = num_guest_funcs;
1915 let deduct_1_func_idx = num_guest_funcs.saturating_add(1);
1916
1917 let (num_guest_globals_u32, raw_globals_tail) =
1919 if let Some(payload) = sec_global {
1920 let mut p = 0usize;
1921 let count = read_uleb_u32(payload, &mut p)?;
1922 let tail = payload
1923 .get(p..)
1924 .context("Truncated WASM Global section payload")?;
1925 (count, tail)
1926 } else {
1927 (0u32, &[][..])
1928 };
1929
1930 let indices = QuotaIndices {
1931 deduct_func_idx,
1932 deduct_1_func_idx,
1933 g_quota_rem: num_guest_globals_u32,
1934 g_quota_consumed: num_guest_globals_u32.saturating_add(1),
1935 g_exhausted: num_guest_globals_u32.saturating_add(2),
1936 g_interrupted_op: num_guest_globals_u32.saturating_add(3),
1937 g_required_cost: num_guest_globals_u32.saturating_add(4),
1938 g_op_ordinal: num_guest_globals_u32.saturating_add(5),
1939 g_total_mem_pages: num_guest_globals_u32.saturating_add(6),
1940 g_max_mem_pages: num_guest_globals_u32.saturating_add(7),
1941 g_phys_max_mem_pages: num_guest_globals_u32.saturating_add(8),
1942 g_total_table_elems: num_guest_globals_u32.saturating_add(9),
1943 g_max_table_elems: num_guest_globals_u32.saturating_add(10),
1944 g_phys_max_table_elems: num_guest_globals_u32.saturating_add(11),
1945 g_resume_target_op: num_guest_globals_u32.saturating_add(12),
1946 };
1947
1948 let start_func_idx = if let Some(payload) = sec_start {
1950 let mut p = 0usize;
1951 Some(read_uleb_u32(payload, &mut p)?)
1952 } else {
1953 None
1954 };
1955
1956 let mut out = Vec::with_capacity(wasm_bytes.len().saturating_mul(2));
1957 out.extend_from_slice(&WASM_HEADER);
1958
1959 {
1961 let mut sec = Vec::with_capacity(raw_types_tail.len().saturating_add(12));
1962 push_uleb_u32(num_guest_types.saturating_add(2), &mut sec);
1963 sec.extend_from_slice(raw_types_tail);
1964 sec.extend_from_slice(&[0x60, 0x01, VALTYPE_I64, 0x00]);
1965 sec.extend_from_slice(&[0x60, 0x00, 0x00]);
1966 push_section(SEC_TYPE, &sec, &mut out)?;
1967 }
1968
1969 if let Some(payload) = sec_import {
1971 push_section(SEC_IMPORT, payload, &mut out)?;
1972 }
1973
1974 {
1976 let mut sec = Vec::with_capacity(raw_funcs_tail.len().saturating_add(8));
1977 push_uleb_u32(num_guest_funcs.saturating_add(2), &mut sec);
1978 sec.extend_from_slice(raw_funcs_tail);
1979 push_uleb_u32(deduct_type_idx, &mut sec);
1980 push_uleb_u32(deduct_1_type_idx, &mut sec);
1981 push_section(SEC_FUNCTION, &sec, &mut out)?;
1982 }
1983
1984 if !parsed_uninstrumented.table_types.is_empty() {
1986 let mut sec = Vec::new();
1987 push_uleb_u32(
1988 u32::try_from(parsed_uninstrumented.table_types.len())?,
1989 &mut sec,
1990 );
1991 for t in &parsed_uninstrumented.table_types {
1992 let elem_byte = match t.element_type {
1993 ctb_formats_dcdata::tinywasm::types::ValType::RefFunc => 0x70,
1994 ctb_formats_dcdata::tinywasm::types::ValType::RefExtern => 0x6F,
1995 other => bail!("Unsupported WASM table element type {other:?}"),
1996 };
1997 let max_clamped = t
2001 .size_max
2002 .unwrap_or(MAX_CLAMPED_DECLARED_TABLE_ELEMENTS)
2003 .min(MAX_CLAMPED_DECLARED_TABLE_ELEMENTS.max(t.size_initial));
2004 sec.push(elem_byte);
2005 sec.push(0x01); push_uleb_u32(t.size_initial, &mut sec);
2007 push_uleb_u32(max_clamped, &mut sec);
2008 }
2009 push_section(SEC_TABLE, &sec, &mut out)?;
2010 } else if let Some(payload) = sec_table {
2011 push_section(SEC_TABLE, payload, &mut out)?;
2012 }
2013
2014 if let Some(payload) = sec_memory {
2016 push_section(SEC_MEMORY, payload, &mut out)?;
2017 }
2018
2019 {
2021 let mut sec =
2022 Vec::with_capacity(raw_globals_tail.len().saturating_add(104));
2023 push_uleb_u32(num_guest_globals_u32.saturating_add(13), &mut sec);
2024 sec.extend_from_slice(raw_globals_tail);
2025
2026 let initial_mem_i64 = i64::try_from(initial_memory_pages)?;
2027 let initial_tbl_i64 = i64::try_from(initial_table_elements)?;
2028 let appended_globals: [(u8, i64); 13] = [
2029 (VALTYPE_I64, i64::MAX), (VALTYPE_I64, 0), (VALTYPE_I32, 0), (VALTYPE_I64, 0), (VALTYPE_I64, 0), (VALTYPE_I64, 0), (VALTYPE_I64, initial_mem_i64), (VALTYPE_I64, 65_536), (VALTYPE_I64, 65_536), (VALTYPE_I64, initial_tbl_i64), (VALTYPE_I64, 65_536), (VALTYPE_I64, 65_536), (VALTYPE_I64, 0), ];
2043 for (vt, init_val) in appended_globals {
2044 sec.push(vt);
2045 sec.push(0x01); if vt == VALTYPE_I64 {
2047 sec.push(0x42); push_sleb_i64(init_val, &mut sec);
2049 } else {
2050 sec.push(0x41); push_sleb_i32(i32::try_from(init_val)?, &mut sec);
2052 }
2053 sec.push(0x0B); }
2055 push_section(SEC_GLOBAL, &sec, &mut out)?;
2056 }
2057
2058 {
2060 let (num_guest_exports, raw_exports_tail) =
2061 if let Some(payload) = sec_export {
2062 let mut p = 0usize;
2063 let count = read_uleb_u32(payload, &mut p)?;
2064 let tail = payload
2065 .get(p..)
2066 .context("Truncated WASM Export section payload")?;
2067 (count, tail)
2068 } else {
2069 (0u32, &[][..])
2070 };
2071 let extra_exports = if start_func_idx.is_some() { 14u32 } else { 13u32 };
2072 let mut sec =
2073 Vec::with_capacity(raw_exports_tail.len().saturating_add(360));
2074 push_uleb_u32(num_guest_exports.saturating_add(extra_exports), &mut sec);
2075 sec.extend_from_slice(raw_exports_tail);
2076
2077 let global_exports: [(&str, u32); 13] = [
2078 (CTB_QUOTA_REMAINING_EXPORT, indices.g_quota_rem),
2079 (CTB_QUOTA_CONSUMED_EXPORT, indices.g_quota_consumed),
2080 (CTB_EXHAUSTED_EXPORT, indices.g_exhausted),
2081 (CTB_INTERRUPTED_OP_EXPORT, indices.g_interrupted_op),
2082 (CTB_REQUIRED_COST_EXPORT, indices.g_required_cost),
2083 (CTB_OP_ORDINAL_EXPORT, indices.g_op_ordinal),
2084 (CTB_TOTAL_MEM_PAGES_EXPORT, indices.g_total_mem_pages),
2085 (CTB_MAX_MEM_PAGES_EXPORT, indices.g_max_mem_pages),
2086 (CTB_PHYS_MAX_MEM_PAGES_EXPORT, indices.g_phys_max_mem_pages),
2087 (CTB_TOTAL_TABLE_ELEMS_EXPORT, indices.g_total_table_elems),
2088 (CTB_MAX_TABLE_ELEMS_EXPORT, indices.g_max_table_elems),
2089 (
2090 CTB_PHYS_MAX_TABLE_ELEMS_EXPORT,
2091 indices.g_phys_max_table_elems,
2092 ),
2093 (CTB_RESUME_TARGET_OP_EXPORT, indices.g_resume_target_op),
2094 ];
2095 for (name, g_idx) in global_exports {
2096 push_name(name, &mut sec)?;
2097 sec.push(0x03); push_uleb_u32(g_idx, &mut sec);
2099 }
2100 if let Some(start_idx) = start_func_idx {
2101 push_name(CTB_WASM_START_EXPORT, &mut sec)?;
2102 sec.push(0x00); push_uleb_u32(start_idx, &mut sec);
2104 }
2105 push_section(SEC_EXPORT, &sec, &mut out)?;
2106 }
2107
2108 if let Some(payload) = sec_element {
2113 push_section(SEC_ELEMENT, payload, &mut out)?;
2114 }
2115
2116 if let Some(payload) = sec_datacount {
2118 push_section(SEC_DATA_COUNT, payload, &mut out)?;
2119 }
2120
2121 {
2123 let mut instrumented_bodies: Vec<Vec<u8>> =
2124 Vec::with_capacity(usize::try_from(num_guest_funcs)?.saturating_add(2));
2125 if let Some(payload) = sec_code {
2126 let mut p = 0usize;
2127 let count = read_uleb_u32(payload, &mut p)?;
2128 ensure!(
2129 count == num_guest_funcs,
2130 "WASM Code section count ({count}) does not match Function section count ({num_guest_funcs})"
2131 );
2132 for func_i in 0..count {
2133 let body_len = usize::try_from(read_uleb_u32(payload, &mut p)?)?;
2134 let body_end = p
2135 .checked_add(body_len)
2136 .context("WASM function body length overflow")?;
2137 let body_slice = payload
2138 .get(p..body_end)
2139 .context("Truncated WASM function body")?;
2140 p = body_end;
2141 let type_idx = *guest_func_type_indices
2142 .get(usize::try_from(func_i)?)
2143 .context(
2144 "WASM function index out of bounds of Function section",
2145 )?;
2146 let ft = parsed_uninstrumented
2147 .func_types
2148 .get(usize::try_from(type_idx)?)
2149 .context(
2150 "WASM function type index out of bounds of Type section",
2151 )?;
2152 let num_params = u32::try_from(ft.params.len())?;
2153 let rewritten = instrument_function_body(
2154 body_slice,
2155 num_params,
2156 &mem_declared_max,
2157 &table_declared_max,
2158 &indices,
2159 )?;
2160 instrumented_bodies.push(rewritten);
2161 }
2162 }
2163 instrumented_bodies.push(encode_deduct_helper_body(&indices));
2164 instrumented_bodies.push(encode_deduct_1_helper_body(&indices));
2165
2166 let mut sec = Vec::new();
2167 push_uleb_u32(u32::try_from(instrumented_bodies.len())?, &mut sec);
2168 for body in &instrumented_bodies {
2169 push_uleb_u32(u32::try_from(body.len())?, &mut sec);
2170 sec.extend_from_slice(body);
2171 }
2172 push_section(SEC_CODE, &sec, &mut out)?;
2173 }
2174
2175 if let Some(payload) = sec_data {
2177 push_section(SEC_DATA, payload, &mut out)?;
2178 }
2179
2180 let parsed_instrumented =
2181 ctb_formats_dcdata::tinywasm::parser::Parser::new()
2182 .parse_module_bytes(&out)
2183 .map_err(|error| {
2184 anyhow!(
2185 "Failed to validate instrumented WebAssembly module: {error:?}"
2186 )
2187 })?;
2188 let parsed_suspendable = build_suspendable_tinywasm_module(
2189 &parsed_instrumented,
2190 deduct_func_idx,
2191 deduct_1_func_idx,
2192 )?;
2193
2194 Ok(InstrumentedWasmModule {
2195 wasm_bytes: out,
2196 parsed_instrumented,
2197 parsed_suspendable,
2198 has_start_func: start_func_idx.is_some(),
2199 initial_memory_pages,
2200 initial_table_elements,
2201 static_data_end,
2202 num_guest_globals,
2203 num_memories,
2204 num_tables,
2205 })
2206}