ctb_formats_dcstring/converters/
wasm_quota.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Portable, runtime-independent WebAssembly compute-quota instrumentation and
21//! shared task-level resource accounting.
22//!
23//! Instruments standard `.wasm` module binaries so that compute-quota deductions
24//! (`deduct-before-effect`), linear-memory and table logical vs. physical growth
25//! checks, and interruption ordinals execute identically on any compliant
26//! WebAssembly runtime (`tinywasm`, V8/Node `WebAssembly`, Wasmtime, etc.)
27//! without requiring a forked WASM engine.
28
29#[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
48/// Exported `i64` global holding the remaining portable compute quota units.
49pub const CTB_QUOTA_REMAINING_EXPORT: &str = "__ctb_quota_remaining";
50/// Exported `i64` global holding the compute quota units consumed in the current run.
51pub const CTB_QUOTA_CONSUMED_EXPORT: &str = "__ctb_quota_consumed";
52/// Exported `i32` global indicating interruption status:
53/// `0 = none`, `1 = ComputeQuotaExhausted`, `2 = MemoryLimitExceeded`, `3 = TableLimitExceeded`.
54pub const CTB_EXHAUSTED_EXPORT: &str = "__ctb_exhausted";
55/// Exported `i64` global recording the 1-based ordinal of the interrupted operation
56/// (or requested total pages/elements on physical growth exhaustion).
57pub const CTB_INTERRUPTED_OP_EXPORT: &str = "__ctb_interrupted_op";
58/// Exported `i64` global recording the compute cost required by the interrupted operation.
59pub const CTB_REQUIRED_COST_EXPORT: &str = "__ctb_required_cost";
60/// Exported `i64` global tracking the 1-based ordinal of metered operations executed.
61pub const CTB_OP_ORDINAL_EXPORT: &str = "__ctb_op_ordinal";
62/// Exported `i64` global tracking total allocated 64 KiB pages across all module memories.
63pub const CTB_TOTAL_MEM_PAGES_EXPORT: &str = "__ctb_total_mem_pages";
64/// Exported `i64` global holding the logical maximum 64 KiB pages (`max_memory_pages`).
65pub const CTB_MAX_MEM_PAGES_EXPORT: &str = "__ctb_max_mem_pages";
66/// Exported `i64` global holding the physical host allocation cap in 64 KiB pages.
67pub const CTB_PHYS_MAX_MEM_PAGES_EXPORT: &str = "__ctb_phys_max_mem_pages";
68/// Exported `i64` global tracking total allocated elements across all module tables.
69pub const CTB_TOTAL_TABLE_ELEMS_EXPORT: &str = "__ctb_total_table_elems";
70/// Exported `i64` global holding the logical maximum table elements (`max_table_elements`).
71pub const CTB_MAX_TABLE_ELEMS_EXPORT: &str = "__ctb_max_table_elems";
72/// Exported `i64` global holding the physical host allocation cap in table elements.
73pub const CTB_PHYS_MAX_TABLE_ELEMS_EXPORT: &str = "__ctb_phys_max_table_elems";
74/// Exported `i64` global specifying the 1-based operation ordinal at which portable
75/// single-threaded continuation replay begins charging quota (`0` = charge from op 1).
76pub const CTB_RESUME_TARGET_OP_EXPORT: &str = "__ctb_resume_target_op";
77/// Exported function name used when a module's `Start` section (`section 8`) is hoisted
78/// for explicit metered execution.
79pub const CTB_WASM_START_EXPORT: &str = "__ctb_wasm_start";
80/// Internal host import module name used by [`DcWasmSession`](super::wasm::DcWasmSession)
81/// to suspend and resume live intra-step continuations on compute-quota exhaustion
82/// and mid-step host capability requests.
83pub const CTB_HOST_IMPORT_MODULE: &str = "__ctb_host";
84/// Internal host import function name used by [`DcWasmSession`](super::wasm::DcWasmSession)
85/// to suspend and resume live intra-step continuations on compute-quota exhaustion.
86pub const CTB_HOST_SUSPEND_IMPORT_NAME: &str = "__ctb_suspend_on_quota";
87/// Internal host import function name used by [`DcWasmSession`](super::wasm::DcWasmSession)
88/// to suspend a live intra-step continuation for a mid-step host capability request.
89pub const CTB_HOST_CAPABILITY_IMPORT_NAME: &str = "__ctb_request_capability";
90/// Optional guest `() -> ()` stub export rewritten at runtime to invoke
91/// [`CTB_HOST_CAPABILITY_IMPORT_NAME`] so standard modules remain zero-import `.wasm`.
92pub 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
118/// Maximum table size declared in Section 4 so that passing `0x4000_0000`
119/// (`1_073_741_824`) on logical denial deterministically exceeds the table's
120/// declared maximum on every WebAssembly engine (`tinywasm`, V8, Wasmtime)
121/// and returns `-1` after popping the reference operand.
122const MAX_CLAMPED_DECLARED_TABLE_ELEMENTS: u32 = 10_000_000;
123
124/// Logical denial sentinel delta passed to `table.grow` (`1_073_741_824`).
125const TABLE_GROW_DENIAL_SENTINEL_DELTA: i32 = 0x4000_0000;
126
127/// Metadata and instrumented `.wasm` bytes produced by [`instrument_wasm_module_bytes`].
128#[derive(Debug, Clone)]
129pub struct InstrumentedWasmModule {
130    /// Standard WebAssembly binary with embedded portable compute-quota and
131    /// logical/physical memory & table growth accounting.
132    pub wasm_bytes: Vec<u8>,
133    /// Validated `TinyWasmModule` parsed from [`Self::wasm_bytes`].
134    pub parsed_instrumented: TinyWasmModule,
135    /// `TinyWasmModule` with `$__ctb_deduct` patched to invoke
136    /// [`CTB_HOST_SUSPEND_IMPORT_NAME`] for live intra-step continuation suspension.
137    pub parsed_suspendable: TinyWasmModule,
138    /// Whether the original module contained a `Start` section (hoisted to
139    /// [`CTB_WASM_START_EXPORT`]).
140    pub has_start_func: bool,
141    /// Sum of initial 64 KiB pages declared across all memories in the module.
142    pub initial_memory_pages: usize,
143    /// Sum of initial elements declared across all tables in the module.
144    pub initial_table_elements: usize,
145    /// Highest byte offset covered by active data segments on memory 0.
146    pub static_data_end: usize,
147    /// Number of guest-defined globals (before the 13 appended `__ctb_*` globals).
148    pub num_guest_globals: usize,
149    /// Number of linear memories declared in the module.
150    pub num_memories: usize,
151    /// Number of tables declared in the module.
152    pub num_tables: usize,
153}
154
155/// Mutable state inside a [`SharedWasmTaskQuota`].
156#[derive(Debug, Clone)]
157pub struct SharedWasmTaskQuotaState {
158    /// Active compiled supervisor resource limits for the current task boundary.
159    pub active_limits: DcWasmResourceLimits,
160    /// Staged supervisor resource limits waiting to take effect at the next explicit
161    /// task or step boundary (never applied mid-execution).
162    pub staged_boundary_limits: Option<DcWasmResourceLimits>,
163    /// Monotonically increasing epoch ordering quota grants, boundary updates,
164    /// and child-task quota allocations/reclamations.
165    pub grant_epoch: u64,
166    /// Remaining compute quota units available across the shared task.
167    pub remaining_compute_quota: u64,
168    /// Active compute quota limit (initial limit plus any granted increases).
169    pub current_compute_quota_limit: u64,
170    /// Total compute quota units executed across all sessions attached to this task.
171    pub total_instructions_executed: u64,
172    /// Cumulative output bytes emitted across all sessions attached to this task.
173    pub cumulative_output_bytes: usize,
174    /// Maximum cumulative output bytes allowed across the shared task.
175    pub max_session_output_bytes: usize,
176    /// Most recent resource interruption raised by any session attached to this task.
177    pub last_resource_interruption: Option<WasmResourceInterruption>,
178}
179
180/// Shared task-level compute and output quota tracker used to ensure that
181/// repeated or nested helper invocations within a single document evaluation task
182/// deduct from one shared allowance rather than silently replenishing quotas.
183#[derive(Debug, Clone)]
184pub struct SharedWasmTaskQuota {
185    inner: Arc<Mutex<SharedWasmTaskQuotaState>>,
186}
187
188impl SharedWasmTaskQuota {
189    /// Creates a new [`SharedWasmTaskQuota`] initialized from `limits`.
190    #[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    /// Returns a snapshot of the active [`DcWasmResourceLimits`] enforced by this shared task quota.
208    ///
209    /// # Errors
210    /// Returns an error if the shared quota mutex is poisoned.
211    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    /// Increases the shared compute quota by `additional_units` and advances `grant_epoch`.
220    ///
221    /// # Errors
222    /// Returns an error if the shared quota mutex is poisoned.
223    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    /// Stages updated [`DcWasmResourceLimits`] to be applied at the next explicit
241    /// task or step boundary via [`Self::apply_staged_boundary_limits`], ensuring
242    /// mutable configuration changes never alter limits mid-instruction.
243    ///
244    /// # Errors
245    /// Returns an error if the shared quota mutex is poisoned.
246    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    /// Applies any staged [`DcWasmResourceLimits`] at an explicit task or step boundary,
259    /// updating active integer counters and advancing `grant_epoch`.
260    ///
261    /// # Errors
262    /// Returns an error if the shared quota mutex is poisoned.
263    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    /// Deterministically carves out a child [`SharedWasmTaskQuota`] from this parent task's
285    /// remaining compute and output allowance at a task boundary, advancing `grant_epoch`.
286    ///
287    /// When the child task finishes or interrupts, call [`Self::reclaim_child_task_quota`]
288    /// to return any unconsumed compute quota and record the child's output usage.
289    ///
290    /// # Errors
291    /// Returns an error if the shared quota mutex is poisoned.
292    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    /// Reclaims unconsumed compute quota from a completed or interrupted child task
322    /// back into this parent task and advances `grant_epoch`.
323    ///
324    /// # Errors
325    /// Returns an error if either shared quota mutex is poisoned.
326    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    /// Returns a snapshot of the current [`SharedWasmTaskQuotaState`].
360    ///
361    /// # Errors
362    /// Returns an error if the shared quota mutex is poisoned.
363    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/// Decoded WebAssembly structured control-flow `blocktype` immediate.
481#[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        // Multi-byte signed s33 type index
585        skip_leb(bytes, pos, 4)?;
586    } else if b == 0x63 || b == 0x64 {
587        // Typed nullable/non-nullable reference `(ref null ht)` / `(ref ht)`
588        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
656/// Maximum straight-line non-loop/non-bulk/non-grow WASM operations permitted
657/// in V2 structural-checkpoint metering before inserting a stride checkpoint.
658pub 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/// Deterministic single-pass V2 checkpoint placement state machine shared by
670/// bytecode instrumentation (`instrument_wasm_module_bytes`) and WASM-to-Rust
671/// substitute transpilation so checkpoint ordinals match bit-for-bit.
672#[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); // call $__ctb_deduct_1
769    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    // Operand stack ends with `[..., n: i32]`.
778    // `local.tee $scratch_delta` keeps `n` on the stack for the bulk op;
779    // `local.get $scratch_delta` pushes a second copy to compute `1 + u64(n)`.
780    out.push(0x22); // local.tee
781    push_uleb_u32(scratch_delta_local, out);
782    out.push(0x20); // local.get
783    push_uleb_u32(scratch_delta_local, out);
784    out.push(0xAD); // i64.extend_i32_u
785    out.push(0x42); // i64.const 1
786    push_sleb_i64(1, out);
787    out.push(0x7C); // i64.add
788    out.push(0x10); // call $__ctb_deduct
789    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    // Pop `delta: i32` into `$scratch_delta`
801    out.push(0x21); // local.set
802    push_uleb_u32(scratch_delta_local, out);
803
804    // Condition 1: `delta < 0`
805    out.push(0x20); // local.get $scratch_delta
806    push_uleb_u32(scratch_delta_local, out);
807    out.push(0x41); // i32.const 0
808    push_sleb_i32(0, out);
809    out.push(0x48); // i32.lt_s
810
811    // Condition 2: `total_mem_pages + u64(delta) > max_mem_pages`
812    out.push(0x23); // global.get $g_total_mem_pages
813    push_uleb_u32(indices.g_total_mem_pages, out);
814    out.push(0x20); // local.get $scratch_delta
815    push_uleb_u32(scratch_delta_local, out);
816    out.push(0xAD); // i64.extend_i32_u
817    out.push(0x7C); // i64.add
818    out.push(0x23); // global.get $g_max_mem_pages
819    push_uleb_u32(indices.g_max_mem_pages, out);
820    out.push(0x56); // i64.gt_u
821
822    // Condition 3: `memory.size(mem_idx) + u64(delta) > declared_max_pages`
823    out.push(0x3F); // memory.size
824    push_uleb_u32(mem_idx, out);
825    out.push(0xAD); // i64.extend_i32_u
826    out.push(0x20); // local.get $scratch_delta
827    push_uleb_u32(scratch_delta_local, out);
828    out.push(0xAD); // i64.extend_i32_u
829    out.push(0x7C); // i64.add
830    out.push(0x42); // i64.const declared_max_pages
831    push_sleb_i64(declared_max_pages, out);
832    out.push(0x56); // i64.gt_u
833
834    out.push(0x72); // i32.or
835    out.push(0x72); // i32.or
836
837    // `if (result i32)`
838    out.push(0x04);
839    out.push(VALTYPE_I32);
840    // Logically denied: deduct 1 unit, push -1
841    emit_deduct_1(indices, out);
842    out.push(0x41); // i32.const -1
843    push_sleb_i32(-1, out);
844    out.push(0x05); // else (logically allowed)
845    // Deduct `1 + 64 * u64(delta)` before effect
846    out.push(0x20); // local.get $scratch_delta
847    push_uleb_u32(scratch_delta_local, out);
848    out.push(0xAD); // i64.extend_i32_u
849    out.push(0x42); // i64.const 64
850    push_sleb_i64(64, out);
851    out.push(0x7E); // i64.mul
852    out.push(0x42); // i64.const 1
853    push_sleb_i64(1, out);
854    out.push(0x7C); // i64.add
855    out.push(0x10); // call $__ctb_deduct
856    push_uleb_u32(indices.deduct_func_idx, out);
857
858    // Check physical host allocation cap: `total_mem_pages + u64(delta) > phys_max_mem_pages`
859    out.push(0x23); // global.get $g_total_mem_pages
860    push_uleb_u32(indices.g_total_mem_pages, out);
861    out.push(0x20); // local.get $scratch_delta
862    push_uleb_u32(scratch_delta_local, out);
863    out.push(0xAD); // i64.extend_i32_u
864    out.push(0x7C); // i64.add
865    out.push(0x23); // global.get $g_phys_max_mem_pages
866    push_uleb_u32(indices.g_phys_max_mem_pages, out);
867    out.push(0x56); // i64.gt_u
868    out.push(0x04); // if (empty)
869    out.push(0x40);
870    out.push(0x41); // i32.const 2 (MemoryLimitExceeded)
871    push_sleb_i32(2, out);
872    out.push(0x24); // global.set $g_exhausted
873    push_uleb_u32(indices.g_exhausted, out);
874    out.push(0x23); // global.get $g_total_mem_pages
875    push_uleb_u32(indices.g_total_mem_pages, out);
876    out.push(0x20); // local.get $scratch_delta
877    push_uleb_u32(scratch_delta_local, out);
878    out.push(0xAD); // i64.extend_i32_u
879    out.push(0x7C); // i64.add
880    out.push(0x24); // global.set $g_interrupted_op (records requested_pages)
881    push_uleb_u32(indices.g_interrupted_op, out);
882    out.push(0x00); // unreachable
883    out.push(0x0B); // end if
884
885    // Execute underlying `memory.grow $mem_idx`
886    out.push(0x20); // local.get $scratch_delta
887    push_uleb_u32(scratch_delta_local, out);
888    out.push(0x40); // memory.grow
889    push_uleb_u32(mem_idx, out);
890    out.push(0x22); // local.tee $scratch_res
891    push_uleb_u32(scratch_res_local, out);
892    out.push(0x41); // i32.const 0
893    push_sleb_i32(0, out);
894    out.push(0x48); // i32.lt_s (engine physical allocation failed despite logical allow)
895    out.push(0x04); // if (empty)
896    out.push(0x40);
897    out.push(0x41); // i32.const 2 (MemoryLimitExceeded)
898    push_sleb_i32(2, out);
899    out.push(0x24); // global.set $g_exhausted
900    push_uleb_u32(indices.g_exhausted, out);
901    out.push(0x23); // global.get $g_total_mem_pages
902    push_uleb_u32(indices.g_total_mem_pages, out);
903    out.push(0x20); // local.get $scratch_delta
904    push_uleb_u32(scratch_delta_local, out);
905    out.push(0xAD); // i64.extend_i32_u
906    out.push(0x7C); // i64.add
907    out.push(0x24); // global.set $g_interrupted_op
908    push_uleb_u32(indices.g_interrupted_op, out);
909    out.push(0x00); // unreachable
910    out.push(0x0B); // end if
911
912    // Update `$g_total_mem_pages += u64(delta)` and push `$scratch_res` (`old_pages`)
913    out.push(0x23); // global.get $g_total_mem_pages
914    push_uleb_u32(indices.g_total_mem_pages, out);
915    out.push(0x20); // local.get $scratch_delta
916    push_uleb_u32(scratch_delta_local, out);
917    out.push(0xAD); // i64.extend_i32_u
918    out.push(0x7C); // i64.add
919    out.push(0x24); // global.set $g_total_mem_pages
920    push_uleb_u32(indices.g_total_mem_pages, out);
921    out.push(0x20); // local.get $scratch_res
922    push_uleb_u32(scratch_res_local, out);
923    out.push(0x0B); // end outer if (result i32)
924}
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    // Operand stack has `[..., init_val: ref, delta: i32]`.
935    // Pop `delta` into `$scratch_delta`, leaving `init_val: ref` on top of the stack.
936    out.push(0x21); // local.set $scratch_delta
937    push_uleb_u32(scratch_delta_local, out);
938
939    // Condition 1: `delta < 0`
940    out.push(0x20); // local.get $scratch_delta
941    push_uleb_u32(scratch_delta_local, out);
942    out.push(0x41); // i32.const 0
943    push_sleb_i32(0, out);
944    out.push(0x48); // i32.lt_s
945
946    // Condition 2: `total_table_elems + u64(delta) > max_table_elems`
947    out.push(0x23); // global.get $g_total_table_elems
948    push_uleb_u32(indices.g_total_table_elems, out);
949    out.push(0x20); // local.get $scratch_delta
950    push_uleb_u32(scratch_delta_local, out);
951    out.push(0xAD); // i64.extend_i32_u
952    out.push(0x7C); // i64.add
953    out.push(0x23); // global.get $g_max_table_elems
954    push_uleb_u32(indices.g_max_table_elems, out);
955    out.push(0x56); // i64.gt_u
956
957    // Condition 3: `table.size(table_idx) + u64(delta) > declared_max_elems`
958    out.push(0xFC); // table.size
959    push_uleb_u32(16, out);
960    push_uleb_u32(table_idx, out);
961    out.push(0xAD); // i64.extend_i32_u
962    out.push(0x20); // local.get $scratch_delta
963    push_uleb_u32(scratch_delta_local, out);
964    out.push(0xAD); // i64.extend_i32_u
965    out.push(0x7C); // i64.add
966    out.push(0x42); // i64.const declared_max_elems
967    push_sleb_i64(declared_max_elems, out);
968    out.push(0x56); // i64.gt_u
969
970    out.push(0x72); // i32.or
971    out.push(0x72); // i32.or
972
973    // `if (result i32)` computes the effective delta to pass to `table.grow`
974    out.push(0x04);
975    out.push(VALTYPE_I32);
976    // Logically denied: deduct 1 unit, mark `$scratch_delta = -1`, push sentinel delta
977    emit_deduct_1(indices, out);
978    out.push(0x41); // i32.const -1
979    push_sleb_i32(-1, out);
980    out.push(0x21); // local.set $scratch_delta
981    push_uleb_u32(scratch_delta_local, out);
982    out.push(0x41); // i32.const TABLE_GROW_DENIAL_SENTINEL_DELTA
983    push_sleb_i32(TABLE_GROW_DENIAL_SENTINEL_DELTA, out);
984    out.push(0x05); // else (logically allowed)
985    // Deduct `1 + u64(delta)` before effect
986    out.push(0x20); // local.get $scratch_delta
987    push_uleb_u32(scratch_delta_local, out);
988    out.push(0xAD); // i64.extend_i32_u
989    out.push(0x42); // i64.const 1
990    push_sleb_i64(1, out);
991    out.push(0x7C); // i64.add
992    out.push(0x10); // call $__ctb_deduct
993    push_uleb_u32(indices.deduct_func_idx, out);
994
995    // Check physical host allocation cap: `total_table_elems + u64(delta) > phys_max_table_elems`
996    out.push(0x23); // global.get $g_total_table_elems
997    push_uleb_u32(indices.g_total_table_elems, out);
998    out.push(0x20); // local.get $scratch_delta
999    push_uleb_u32(scratch_delta_local, out);
1000    out.push(0xAD); // i64.extend_i32_u
1001    out.push(0x7C); // i64.add
1002    out.push(0x23); // global.get $g_phys_max_table_elems
1003    push_uleb_u32(indices.g_phys_max_table_elems, out);
1004    out.push(0x56); // i64.gt_u
1005    out.push(0x04); // if (empty)
1006    out.push(0x40);
1007    out.push(0x41); // i32.const 3 (TableLimitExceeded)
1008    push_sleb_i32(3, out);
1009    out.push(0x24); // global.set $g_exhausted
1010    push_uleb_u32(indices.g_exhausted, out);
1011    out.push(0x23); // global.get $g_total_table_elems
1012    push_uleb_u32(indices.g_total_table_elems, out);
1013    out.push(0x20); // local.get $scratch_delta
1014    push_uleb_u32(scratch_delta_local, out);
1015    out.push(0xAD); // i64.extend_i32_u
1016    out.push(0x7C); // i64.add
1017    out.push(0x24); // global.set $g_interrupted_op (records requested_elements)
1018    push_uleb_u32(indices.g_interrupted_op, out);
1019    out.push(0x00); // unreachable
1020    out.push(0x0B); // end if
1021
1022    out.push(0x20); // local.get $scratch_delta
1023    push_uleb_u32(scratch_delta_local, out);
1024    out.push(0x0B); // end if (result i32)
1025
1026    // Stack now has `[..., init_val: ref, effective_delta: i32]`.
1027    // Execute `table.grow $table_idx`
1028    out.push(0xFC);
1029    push_uleb_u32(15, out);
1030    push_uleb_u32(table_idx, out);
1031    out.push(0x22); // local.tee $scratch_res
1032    push_uleb_u32(scratch_res_local, out);
1033
1034    // If `$scratch_delta >= 0` (logically allowed branch was taken):
1035    out.push(0x20); // local.get $scratch_delta
1036    push_uleb_u32(scratch_delta_local, out);
1037    out.push(0x41); // i32.const 0
1038    push_sleb_i32(0, out);
1039    out.push(0x4E); // i32.ge_s
1040    out.push(0x04); // if (empty)
1041    out.push(0x40);
1042    // If `$scratch_res < 0`, underlying engine failed physical table growth
1043    out.push(0x20); // local.get $scratch_res
1044    push_uleb_u32(scratch_res_local, out);
1045    out.push(0x41); // i32.const 0
1046    push_sleb_i32(0, out);
1047    out.push(0x48); // i32.lt_s
1048    out.push(0x04); // if (empty)
1049    out.push(0x40);
1050    out.push(0x41); // i32.const 3 (TableLimitExceeded)
1051    push_sleb_i32(3, out);
1052    out.push(0x24); // global.set $g_exhausted
1053    push_uleb_u32(indices.g_exhausted, out);
1054    out.push(0x23); // global.get $g_total_table_elems
1055    push_uleb_u32(indices.g_total_table_elems, out);
1056    out.push(0x20); // local.get $scratch_delta
1057    push_uleb_u32(scratch_delta_local, out);
1058    out.push(0xAD); // i64.extend_i32_u
1059    out.push(0x7C); // i64.add
1060    out.push(0x24); // global.set $g_interrupted_op
1061    push_uleb_u32(indices.g_interrupted_op, out);
1062    out.push(0x00); // unreachable
1063    out.push(0x0B); // end if
1064
1065    // Update `$g_total_table_elems += u64(delta)`
1066    out.push(0x23); // global.get $g_total_table_elems
1067    push_uleb_u32(indices.g_total_table_elems, out);
1068    out.push(0x20); // local.get $scratch_delta
1069    push_uleb_u32(scratch_delta_local, out);
1070    out.push(0xAD); // i64.extend_i32_u
1071    out.push(0x7C); // i64.add
1072    out.push(0x24); // global.set $g_total_table_elems
1073    push_uleb_u32(indices.g_total_table_elems, out);
1074    out.push(0x0B); // end if
1075}
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    // Deduct 1 compute unit on function entry
1115    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        // Final `end` of the function body
1123        if opcode == 0x0B && pos == body_bytes.len() {
1124            out.push(0x0B);
1125            break;
1126        }
1127
1128        // Structural delimiter `else` (0x05)
1129        if opcode == 0x05 {
1130            planner.on_else();
1131            out.push(0x05);
1132            continue;
1133        }
1134
1135        // Nested structural delimiter `end` (0x0B)
1136        if opcode == 0x0B {
1137            planner.on_end();
1138            out.push(0x0B);
1139            continue;
1140        }
1141
1142        // `loop <blocktype>` (0x03): emit loop header, then deduct 1 unit at loop body entry
1143        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        // `block <blocktype>` (0x02) / `if <blocktype>` (0x04)
1154        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        // `memory.grow $mem_idx` (0x40)
1166        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        // `0xFC` prefix instructions
1186        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                    // `memory.init` (8), `memory.copy` (10), `table.init` (12), `table.copy` (14)
1199                    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                    // `memory.fill` (11), `table.fill` (17)
1209                    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                    // `table.size` (16), `data.drop` (9), `elem.drop` (13)
1218                    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                    // `table.grow $table_idx`
1228                    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        // `0xFB` GC prefix instructions (gated in BootstrapKernelVersion::V1)
1250        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        // `0xFD` SIMD prefix instructions
1257        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        // Standard single-byte instructions (`block` / `if` handled above)
1294        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); // 0 local runs (1 param: `$cost: i64` at local 0)
1363
1364    // `__ctb_op_ordinal = __ctb_op_ordinal + 1`
1365    body.push(0x23); // global.get $g_op_ordinal
1366    push_uleb_u32(indices.g_op_ordinal, &mut body);
1367    body.push(0x42); // i64.const 1
1368    push_sleb_i64(1, &mut body);
1369    body.push(0x7C); // i64.add
1370    body.push(0x24); // global.set $g_op_ordinal
1371    push_uleb_u32(indices.g_op_ordinal, &mut body);
1372
1373    // If `__ctb_op_ordinal < __ctb_resume_target_op`, this operation was already
1374    // executed and paid for prior to the continuation checkpoint; return without
1375    // deducting from `__ctb_quota_remaining` or adding to `__ctb_quota_consumed`.
1376    body.push(0x23); // global.get $g_op_ordinal
1377    push_uleb_u32(indices.g_op_ordinal, &mut body);
1378    body.push(0x23); // global.get $g_resume_target_op
1379    push_uleb_u32(indices.g_resume_target_op, &mut body);
1380    body.push(0x54); // i64.lt_u
1381    body.push(0x04); // if (empty)
1382    body.push(0x40);
1383    body.push(0x0F); // return
1384    body.push(0x0B); // end if
1385
1386    // `loop $wait_for_quota`
1387    body.push(0x03); // loop (empty)
1388    body.push(0x40);
1389    // `if (i64.lt_u(global.get $g_quota_rem, local.get 0))`
1390    body.push(0x23); // global.get $g_quota_rem
1391    push_uleb_u32(indices.g_quota_rem, &mut body);
1392    body.push(0x20); // local.get 0 ($cost)
1393    push_uleb_u32(0, &mut body);
1394    body.push(0x54); // i64.lt_u
1395    body.push(0x04); // if (empty)
1396    body.push(0x40);
1397    body.push(0x41); // i32.const 1 (ComputeQuotaExhausted)
1398    push_sleb_i32(1, &mut body);
1399    body.push(0x24); // global.set $g_exhausted
1400    push_uleb_u32(indices.g_exhausted, &mut body);
1401    body.push(0x23); // global.get $g_op_ordinal
1402    push_uleb_u32(indices.g_op_ordinal, &mut body);
1403    body.push(0x24); // global.set $g_interrupted_op
1404    push_uleb_u32(indices.g_interrupted_op, &mut body);
1405    body.push(0x20); // local.get 0 ($cost)
1406    push_uleb_u32(0, &mut body);
1407    body.push(0x24); // global.set $g_required_cost
1408    push_uleb_u32(indices.g_required_cost, &mut body);
1409    body.push(0x00); // unreachable (replaced by `call $__ctb_suspend_on_quota` in `parsed_suspendable`)
1410    body.push(0x0C); // br 1 (re-evaluates `$wait_for_quota` loop after suspension resumes)
1411    push_uleb_u32(1, &mut body);
1412    body.push(0x0B); // end if
1413    body.push(0x0B); // end loop
1414
1415    // `__ctb_quota_remaining -= $cost`
1416    body.push(0x23); // global.get $g_quota_rem
1417    push_uleb_u32(indices.g_quota_rem, &mut body);
1418    body.push(0x20); // local.get 0 ($cost)
1419    push_uleb_u32(0, &mut body);
1420    body.push(0x7D); // i64.sub
1421    body.push(0x24); // global.set $g_quota_rem
1422    push_uleb_u32(indices.g_quota_rem, &mut body);
1423
1424    // `__ctb_quota_consumed += $cost`
1425    body.push(0x23); // global.get $g_quota_consumed
1426    push_uleb_u32(indices.g_quota_consumed, &mut body);
1427    body.push(0x20); // local.get 0 ($cost)
1428    push_uleb_u32(0, &mut body);
1429    body.push(0x7C); // i64.add
1430    body.push(0x24); // global.set $g_quota_consumed
1431    push_uleb_u32(indices.g_quota_consumed, &mut body);
1432
1433    body.push(0x0B); // end function
1434    body
1435}
1436
1437/// Encodes zero-argument `$__ctb_deduct_1()` for fixed cost `1` V2 structural
1438/// checkpoints (function entry, `loop` entry, straight-line stride cap, and
1439/// logically denied `memory.grow` / `table.grow`).
1440fn encode_deduct_1_helper_body(indices: &QuotaIndices) -> Vec<u8> {
1441    let mut body = Vec::with_capacity(88);
1442    body.push(0x00); // 0 local runs (0 params, 0 locals)
1443
1444    // `__ctb_op_ordinal = __ctb_op_ordinal + 1`
1445    body.push(0x23); // global.get $g_op_ordinal
1446    push_uleb_u32(indices.g_op_ordinal, &mut body);
1447    body.push(0x42); // i64.const 1
1448    push_sleb_i64(1, &mut body);
1449    body.push(0x7C); // i64.add
1450    body.push(0x24); // global.set $g_op_ordinal
1451    push_uleb_u32(indices.g_op_ordinal, &mut body);
1452
1453    // Continuation replay fast-forward check
1454    body.push(0x23); // global.get $g_op_ordinal
1455    push_uleb_u32(indices.g_op_ordinal, &mut body);
1456    body.push(0x23); // global.get $g_resume_target_op
1457    push_uleb_u32(indices.g_resume_target_op, &mut body);
1458    body.push(0x54); // i64.lt_u
1459    body.push(0x04); // if (empty)
1460    body.push(0x40);
1461    body.push(0x0F); // return
1462    body.push(0x0B); // end if
1463
1464    // `loop $wait_for_quota`
1465    body.push(0x03); // loop (empty)
1466    body.push(0x40);
1467    // `if (__ctb_quota_remaining < 1)` (`i64.eqz` since remaining is u64)
1468    body.push(0x23); // global.get $g_quota_rem
1469    push_uleb_u32(indices.g_quota_rem, &mut body);
1470    body.push(0x50); // i64.eqz
1471    body.push(0x04); // if (empty)
1472    body.push(0x40);
1473    body.push(0x41); // i32.const 1 (ComputeQuotaExhausted)
1474    push_sleb_i32(1, &mut body);
1475    body.push(0x24); // global.set $g_exhausted
1476    push_uleb_u32(indices.g_exhausted, &mut body);
1477    body.push(0x23); // global.get $g_op_ordinal
1478    push_uleb_u32(indices.g_op_ordinal, &mut body);
1479    body.push(0x24); // global.set $g_interrupted_op
1480    push_uleb_u32(indices.g_interrupted_op, &mut body);
1481    body.push(0x42); // i64.const 1
1482    push_sleb_i64(1, &mut body);
1483    body.push(0x24); // global.set $g_required_cost
1484    push_uleb_u32(indices.g_required_cost, &mut body);
1485    body.push(0x00); // unreachable (replaced by `call $__ctb_suspend_on_quota` in `parsed_suspendable`)
1486    body.push(0x0C); // br 1 (re-evaluates `$wait_for_quota` loop after suspension resumes)
1487    push_uleb_u32(1, &mut body);
1488    body.push(0x0B); // end if
1489    body.push(0x0B); // end loop
1490
1491    // `__ctb_quota_remaining -= 1`
1492    body.push(0x23); // global.get $g_quota_rem
1493    push_uleb_u32(indices.g_quota_rem, &mut body);
1494    body.push(0x42); // i64.const 1
1495    push_sleb_i64(1, &mut body);
1496    body.push(0x7D); // i64.sub
1497    body.push(0x24); // global.set $g_quota_rem
1498    push_uleb_u32(indices.g_quota_rem, &mut body);
1499
1500    // `__ctb_quota_consumed += 1`
1501    body.push(0x23); // global.get $g_quota_consumed
1502    push_uleb_u32(indices.g_quota_consumed, &mut body);
1503    body.push(0x42); // i64.const 1
1504    push_sleb_i64(1, &mut body);
1505    body.push(0x7C); // i64.add
1506    body.push(0x24); // global.set $g_quota_consumed
1507    push_uleb_u32(indices.g_quota_consumed, &mut body);
1508
1509    body.push(0x0B); // end function
1510    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/// Validates and instruments a standard WebAssembly module binary with portable
1730/// `deduct-before-effect` compute-quota accounting and logical/physical memory
1731/// and table growth guards.
1732///
1733/// # Errors
1734/// Returns an error if `wasm_bytes` is not a valid WebAssembly module, declares
1735/// host imports or `memory64`, declares any reserved `"__ctb_*"` export, or uses
1736/// unsupported opcodes.
1737#[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            // Reason for fallback: in the WebAssembly specification, a 32-bit memory without an
1818            // explicit maximum (`None`) has an architectural maximum of 65,536 pages (4 GiB).
1819            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            // Reason for fallback: an unbounded table (`size_max == None`) is clamped to
1828            // MAX_CLAMPED_DECLARED_TABLE_ELEMENTS so the logical-denial sentinel delta
1829            // (`TABLE_GROW_DENIAL_SENTINEL_DELTA`) always exceeds the declared table limit.
1830            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    // 1. Parse Type section count
1885    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    // 3. Parse Function section and collect each guest function's parameter count
1899    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    // 6. Parse Global section count
1918    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    // 8. Parse Start section if present
1949    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    // Emit Section 1 (Type): original types + `(func (param i64))` + `(func ())`
1960    {
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    // Emit Section 2 (Import) if present
1970    if let Some(payload) = sec_import {
1971        push_section(SEC_IMPORT, payload, &mut out)?;
1972    }
1973
1974    // Emit Section 3 (Function): original functions + `$__ctb_deduct` + `$__ctb_deduct_1`
1975    {
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    // Emit Section 4 (Table) with clamped declared maximums (`<= 10_000_000`)
1985    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            // Reason for fallback: an unbounded table (`size_max == None`) is clamped to
1998            // MAX_CLAMPED_DECLARED_TABLE_ELEMENTS so the logical-denial sentinel delta
1999            // (`TABLE_GROW_DENIAL_SENTINEL_DELTA`) always exceeds the declared table limit.
2000            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); // has max
2006            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    // Emit Section 5 (Memory)
2015    if let Some(payload) = sec_memory {
2016        push_section(SEC_MEMORY, payload, &mut out)?;
2017    }
2018
2019    // Emit Section 6 (Global): original globals + 13 `__ctb_*` globals
2020    {
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),        // __ctb_quota_remaining
2030            (VALTYPE_I64, 0),               // __ctb_quota_consumed
2031            (VALTYPE_I32, 0),               // __ctb_exhausted
2032            (VALTYPE_I64, 0),               // __ctb_interrupted_op
2033            (VALTYPE_I64, 0),               // __ctb_required_cost
2034            (VALTYPE_I64, 0),               // __ctb_op_ordinal
2035            (VALTYPE_I64, initial_mem_i64), // __ctb_total_mem_pages
2036            (VALTYPE_I64, 65_536),          // __ctb_max_mem_pages
2037            (VALTYPE_I64, 65_536),          // __ctb_phys_max_mem_pages
2038            (VALTYPE_I64, initial_tbl_i64), // __ctb_total_table_elems
2039            (VALTYPE_I64, 65_536),          // __ctb_max_table_elems
2040            (VALTYPE_I64, 65_536),          // __ctb_phys_max_table_elems
2041            (VALTYPE_I64, 0),               // __ctb_resume_target_op
2042        ];
2043        for (vt, init_val) in appended_globals {
2044            sec.push(vt);
2045            sec.push(0x01); // mutable
2046            if vt == VALTYPE_I64 {
2047                sec.push(0x42); // i64.const
2048                push_sleb_i64(init_val, &mut sec);
2049            } else {
2050                sec.push(0x41); // i32.const
2051                push_sleb_i32(i32::try_from(init_val)?, &mut sec);
2052            }
2053            sec.push(0x0B); // end
2054        }
2055        push_section(SEC_GLOBAL, &sec, &mut out)?;
2056    }
2057
2058    // Emit Section 7 (Export): original exports + 13 `__ctb_*` globals + optional `__ctb_wasm_start`
2059    {
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); // global export
2098            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); // func export
2103            push_uleb_u32(start_idx, &mut sec);
2104        }
2105        push_section(SEC_EXPORT, &sec, &mut out)?;
2106    }
2107
2108    // Note: Section 8 (Start) is intentionally omitted and exported as `CTB_WASM_START_EXPORT`
2109    // so the host initializes the compute-quota globals before running `start`.
2110
2111    // Emit Section 9 (Element) if present
2112    if let Some(payload) = sec_element {
2113        push_section(SEC_ELEMENT, payload, &mut out)?;
2114    }
2115
2116    // Emit Section 12 (DataCount) if present
2117    if let Some(payload) = sec_datacount {
2118        push_section(SEC_DATA_COUNT, payload, &mut out)?;
2119    }
2120
2121    // Emit Section 10 (Code): instrumented guest function bodies + `$__ctb_deduct` + `$__ctb_deduct_1`
2122    {
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    // Emit Section 11 (Data) if present
2176    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}