lib.rs

cdk-rsx/crates/cdk-rsx-wasm/src/lib.rs

lib.rs1,047 lines← SDK documentation
1//! Build-time validation and controlled startup for the cdk-rsx memory profile.2use anyhow::{Context, Result, bail, ensure};3use cdk_rsx_platform::profile;4use cdk_rsx_platform::profile::MemoryProfile;5use serde_json::{Value, json};6use wasm_encoder as enc;7use wasmparser::{8    DataKind, ExternalKind, FuncType, Operator, Parser, Payload, TypeRef, ValType, Validator,9    WasmFeatures,10};1112mod compatibility_inventory;13pub mod origin;14pub use compatibility_inventory::inventory as compatibility;1516pub const STACK_SIZE: u64 = profile::STACK_SIZE as u64;17pub const STATIC_LIMIT: u64 = profile::STATIC_LIMIT as u64;18pub const EOP_NAME: &str = "icp:private enhanced-orthogonal-persistence";19pub const PROFILE_NAME: &str = "icp:public cdk-rsx-memory-profile";20pub const WIRE_NAME: &str = "icp:public cdk-rsx:wire";21/// Compiler-emitted controlled-protocol method names, excluded from public Wire interface.22pub const RAW_METHODS_NAME: &str = "cdk-rsx:raw-methods";23/// Closed typed-root lifecycle hook, consumed by the startup transformer.24pub const ABI_ADMIT_EXPORT: &str = "__cdk_rsx_memory_abi_admit";2526/// Deliberate IC feature allowlist; new wasmparser defaults cannot broaden it.27pub fn features() -> WasmFeatures {28    WasmFeatures::FLOATS29        | WasmFeatures::MUTABLE_GLOBAL30        | WasmFeatures::SATURATING_FLOAT_TO_INT31        | WasmFeatures::SIGN_EXTENSION32        | WasmFeatures::REFERENCE_TYPES33        | WasmFeatures::MULTI_VALUE34        | WasmFeatures::BULK_MEMORY35        | WasmFeatures::SIMD36        | WasmFeatures::TAIL_CALL37        | WasmFeatures::MEMORY6438}3940/// Select artifact geometry from its declared memory, never the native tool's41/// COMPILED_PROFILE. This scan reads section headers, not function operators.42fn memory_profile(raw: &[u8]) -> Result<MemoryProfile> {43    let mut memory = None;44    for payload in Parser::new(0).parse_all(raw) {45        match payload? {46            Payload::ImportSection(reader) => {47                for import in reader.into_imports() {48                    ensure!(49                        !matches!(import?.ty, TypeRef::Memory(_)),50                        "imported memory unsupported"51                    );52                }53            }54            Payload::MemorySection(reader) => {55                for item in reader {56                    ensure!(memory.is_none(), "exactly one user memory required");57                    memory = Some(item?);58                }59            }60            _ => {}61        }62    }63    let memory = memory.context("exactly one user memory required")?;64    ensure!(65        !memory.shared && memory.page_size_log2.is_none(),66        "non-shared memory with ordinary pages required"67    );68    Ok(if memory.memory64 {69        MemoryProfile::Wasm6470    } else {71        MemoryProfile::Wasm3272    })73}7475fn pointer_type(profile: MemoryProfile) -> ValType {76    match profile {77        MemoryProfile::Wasm32 => ValType::I32,78        MemoryProfile::Wasm64 => ValType::I64,79    }80}8182fn constant(expr: wasmparser::ConstExpr<'_>, profile: MemoryProfile) -> Result<u64> {83    let mut ops = expr.get_operators_reader();84    let value = match (profile, ops.read()?) {85        (MemoryProfile::Wasm32, Operator::I32Const { value }) => u64::from(value as u32),86        (MemoryProfile::Wasm64, Operator::I64Const { value }) => value as u64,87        _ => bail!("constant i{} initializer required", profile.pointer_width()),88    };89    ensure!(90        matches!(ops.read()?, Operator::End) && ops.eof(),91        "unsupported constant expression"92    );93    Ok(value)94}9596fn address(profile: MemoryProfile, value: u64) -> Result<enc::Instruction<'static>> {97    Ok(match profile {98        MemoryProfile::Wasm32 => enc::Instruction::I32Const(u32::try_from(value)? as i32),99        MemoryProfile::Wasm64 => enc::Instruction::I64Const(i64::try_from(value)?),100    })101}102103fn memory_size_u64(body: &mut enc::Function, profile: MemoryProfile) {104    body.instruction(&enc::Instruction::MemorySize(0));105    if profile == MemoryProfile::Wasm32 {106        body.instruction(&enc::Instruction::I64ExtendI32U);107    }108}109110/// Only ABI-sized operands follow the module's memory width. Fixed quantities111/// and all stable64 operands retain their specified widths on both profiles.112fn check_import(name: &str, ty: &FuncType, profile: MemoryProfile) -> Result<()> {113    use ValType::{I32, I64};114    let p = pointer_type(profile);115    let (params, results): (&[ValType], &[ValType]) = match name {116        "msg_arg_data_size"117        | "msg_caller_size"118        | "msg_caller_info_data_size"119        | "msg_caller_info_signer_size"120        | "msg_reject_msg_size"121        | "canister_self_size"122        | "subnet_self_size"123        | "msg_method_name_size"124        | "root_key_size"125        | "data_certificate_size"126        | "env_var_count" => (&[], &[p]),127        "msg_deadline" | "canister_version" | "time" | "stable64_size" => (&[], &[I64]),128        "msg_arg_data_copy"129        | "msg_caller_copy"130        | "msg_caller_info_data_copy"131        | "msg_caller_info_signer_copy"132        | "msg_reject_msg_copy"133        | "canister_self_copy"134        | "subnet_self_copy"135        | "msg_method_name_copy"136        | "root_key_copy"137        | "data_certificate_copy"138        | "cost_http_request_v2" => (&[p, p, p], &[]),139        "msg_cycles_accept128" | "cycles_burn128" | "cost_call" | "cost_http_request" => {140            (&[I64, I64, p], &[])141        }142        "stable64_read" | "stable64_write" => (&[I64, I64, I64], &[]),143        "msg_reject_code"144        | "canister_status"145        | "subnet_self_node_count"146        | "call_perform"147        | "data_certificate_present"148        | "in_replicated_execution" => (&[], &[I32]),149        "msg_reply_data_append"150        | "msg_reject"151        | "call_on_cleanup"152        | "call_data_append"153        | "certified_data_set"154        | "debug_print"155        | "trap" => (&[p, p], &[]),156        "call_cycles_add128" => (&[I64, I64], &[]),157        "msg_reply" | "accept_message" => (&[], &[]),158        "msg_cycles_available128"159        | "msg_cycles_refunded128"160        | "canister_cycle_balance128"161        | "canister_liquid_cycle_balance128"162        | "cost_create_canister" => (&[p], &[]),163        "call_new" => (&[p, p, p, p, p, p, p, p], &[]),164        "call_with_best_effort_response" => (&[I32], &[]),165        "global_timer_set" | "stable64_grow" => (&[I64], &[I64]),166        "env_var_name_size" => (&[p], &[p]),167        "performance_counter" => (&[I32], &[I64]),168        "is_controller" | "env_var_name_exists" => (&[p, p], &[I32]),169        "cost_sign_with_ecdsa" | "cost_sign_with_schnorr" | "cost_vetkd_derive_key" => {170            (&[p, p, I32, p], &[I32])171        }172        "env_var_name_copy" => (&[p, p, p, p], &[]),173        "env_var_value_size" => (&[p, p], &[p]),174        "env_var_value_copy" => (&[p, p, p, p, p], &[]),175        _ => bail!("unsupported ic0 import {name}"),176    };177    ensure!(178        ty.params() == params && ty.results() == results,179        "wrong wasm{} IC signature for ic0.{name}",180        profile.pointer_width()181    );182    Ok(())183}184185pub mod page_profile;186187/// Prepare the closed typed-root lifecycle. Compiled catalog admission runs188/// after fresh static replay and before retained allocator/module pointers.189/// Diagnostic names remain in the raw host artifact, outside the installed image.190pub fn transform(raw: &[u8], wire: Option<&str>) -> Result<(Vec<u8>, Value)> {191    transform_impl(raw, wire, false)192}193194/// Prepare while retaining the custom name section for canister backtraces.195pub fn transform_with_names(raw: &[u8], wire: Option<&str>) -> Result<(Vec<u8>, Value)> {196    transform_impl(raw, wire, true)197}198199fn transform_impl(raw: &[u8], wire: Option<&str>, keep_names: bool) -> Result<(Vec<u8>, Value)> {200    page_profile::check_final(raw)?;201    Validator::new_with_features(features())202        .validate_all(raw)203        .context("input is not valid for the IC feature profile")?;204    let memory_profile = memory_profile(raw)?;205    let initial_memory = profile::INITIAL_MEMORY;206    let mut sections = Vec::new();207    let mut types = Vec::new();208    let mut functions = Vec::new();209    let mut imported = Vec::new();210    let mut globals = Vec::new();211    let mut exports = Vec::new();212    let mut bodies = Vec::new();213    let mut data = Vec::new();214    let mut copies = Vec::new();215    for payload in Parser::new(0).parse_all(raw) {216        let payload = payload?;217        if let Some(section) = payload.as_section()218            && (keep_names || !matches!(&payload, Payload::CustomSection(s) if s.name() == "name"))219        {220            sections.push(section);221        }222        match payload {223            Payload::TypeSection(reader) => types.extend(224                reader225                    .into_iter_err_on_gc_types()226                    .collect::<std::result::Result<Vec<_>, _>>()?,227            ),228            Payload::ImportSection(reader) => {229                for import in reader.into_imports() {230                    let import = import?;231                    ensure!(import.module == "ic0", "only IC system imports supported");232                    let TypeRef::Func(index) = import.ty else {233                        bail!("only function imports supported")234                    };235                    check_import(import.name, &types[index as usize], memory_profile)?;236                    imported.push(index);237                }238            }239            Payload::FunctionSection(reader) => functions.extend(240                reader241                    .into_iter()242                    .collect::<std::result::Result<Vec<_>, _>>()?,243            ),244            Payload::MemorySection(reader) => {245                ensure!(reader.count() == 1, "exactly one user memory required");246                let memory = reader.into_iter().next().unwrap()?;247                ensure!(248                    !memory.shared && memory.page_size_log2.is_none(),249                    "non-shared memory with ordinary pages required"250                );251                ensure!(252                    memory.maximum253                        == Some(memory_profile.address_limit() / profile::WASM_PAGE as u64),254                    "link with --max-memory={}",255                    memory_profile.address_limit()256                );257                ensure!(258                    memory.initial == initial_memory as u64 / profile::WASM_PAGE as u64,259                    "link with --initial-memory={}",260                    initial_memory261                );262            }263            Payload::GlobalSection(reader) => {264                for global in reader {265                    let global = global?;266                    ensure!(267                        global.ty.content_type == pointer_type(memory_profile) && !global.ty.shared,268                        "only non-shared i{} globals supported",269                        memory_profile.pointer_width()270                    );271                    globals.push((272                        constant(global.init_expr, memory_profile)?,273                        global.ty.mutable,274                    ));275                }276            }277            Payload::ExportSection(reader) => exports.extend(278                reader279                    .into_iter()280                    .collect::<std::result::Result<Vec<_>, _>>()?,281            ),282            Payload::CodeSectionEntry(body) => bodies.push(body.range()),283            Payload::DataSection(reader) => {284                for (index, item) in reader.into_iter().enumerate() {285                    let item = item?;286                    if let DataKind::Active {287                        memory_index,288                        offset_expr,289                    } = item.kind290                    {291                        ensure!(memory_index == 0, "multiple memories unsupported");292                        let offset = constant(offset_expr, memory_profile)?;293                        ensure!(294                            offset >= profile::STATIC_DATA_BASE as u64295                                && offset296                                    .checked_add(item.data.len() as u64)297                                    .is_some_and(|end| end <= STATIC_LIMIT),298                            "active data crosses protected zones"299                        );300                        copies.push((301                            u32::try_from(index)?,302                            offset,303                            u32::try_from(item.data.len())?,304                        ));305                    }306                    data.push(item.data);307                }308            }309            Payload::StartSection { .. } => {310                bail!("start functions require a separately qualified startup profile")311            }312            Payload::TagSection(_) => bail!("exception tags unsupported"),313            Payload::CustomSection(section) => {314                ensure!(315                    !matches!(316                        section.name(),317                        EOP_NAME318                            | PROFILE_NAME319                            | "icp:public enhanced-orthogonal-persistence"320                            | "icp:private cdk-rsx-memory-profile"321                    ),322                    "already transformed"323                );324                ensure!(325                    !matches!(326                        section.name(),327                        WIRE_NAME | "icp:private candid:service" | "icp:public candid:service"328                    ),329                    "public interface metadata already present"330                );331            }332            _ => {}333        }334    }335    for id in [1, 3, 5, 6, 7, 10] {336        ensure!(337            sections.iter().any(|(present, _)| *present == id),338            "missing required section {id}"339        );340    }341    let mut methods = std::collections::BTreeSet::new();342    for e in &exports {343        if !e.name.starts_with("canister_") {344            continue;345        }346        ensure!(347            e.kind == ExternalKind::Func,348            "IC entrypoint must be a function"349        );350        if let Some(name) = e351            .name352            .strip_prefix("canister_update ")353            .or_else(|| e.name.strip_prefix("canister_query "))354            .or_else(|| e.name.strip_prefix("canister_composite_query "))355        {356            ensure!(methods.insert(name), "duplicate IC method {name}");357            if name.starts_with("<cdk-rsx internal>") {358                ensure!(359                    e.name == "canister_update <cdk-rsx internal> timer_executor",360                    "unknown reserved SDK entrypoint"361                );362                ensure!(363                    exports.iter().any(|e| e.name == "canister_global_timer"),364                    "timer executor requires global timer entrypoint"365                );366            }367        } else {368            ensure!(369                matches!(370                    e.name,371                    "canister_init"372                        | "canister_pre_upgrade"373                        | "canister_post_upgrade"374                        | "canister_inspect_message"375                        | "canister_heartbeat"376                        | "canister_global_timer"377                        | "canister_on_low_wasm_memory"378                ),379                "unknown IC export {}",380                e.name381            );382        }383        let index = e.index as usize;384        let type_index = if index < imported.len() {385            imported[index]386        } else {387            functions[index - imported.len()]388        };389        let ty = &types[type_index as usize];390        ensure!(391            ty.params().is_empty() && ty.results().is_empty(),392            "IC entrypoint {} must have signature () -> ()",393            e.name394        );395    }396    let export = |name: &str| {397        exports.iter().find(|e| e.name == name).with_context(|| {398            if name == ABI_ADMIT_EXPORT {399                format!(400                    "missing required export {name}. Use `#[cdk_rsx::root(state = ...)]` \401                     to generate the admission export, as shown in Quickstart."402                )403            } else {404                format!("missing required export {name}")405            }406        })407    };408    ensure!(409        !exports410            .iter()411            .any(|e| e.name == "canister_query __get_candid_interface_tmp_hack"),412        "obsolete Candid discovery export"413    );414    let global = |name: &str, mutable: bool| -> Result<u64> {415        let e = export(name)?;416        ensure!(e.kind == ExternalKind::Global, "{name} must be a global");417        let &(value, actual_mutable) = globals.get(e.index as usize).context("unknown global")?;418        ensure!(actual_mutable == mutable, "wrong mutability for {name}");419        Ok(value)420    };421    let heap_base = global("__heap_base", false)?;422    let data_end = global("__data_end", false)?;423    ensure!(424        (profile::STATIC_DATA_BASE as u64..=STATIC_LIMIT).contains(&heap_base)425            && (profile::STATIC_DATA_BASE as u64..=heap_base).contains(&data_end),426        "stack/statics exceed their reserved zone"427    );428    // The linker includes zero-initialized BSS/TLS in __data_end even when429    // those bytes have no active data segment. Prove every initializer agrees430    // with that bound before using it to restrict startup writes.431    ensure!(432        copies.iter().all(|&(_, offset, len)| offset433            .checked_add(u64::from(len))434            .is_some_and(|end| end <= data_end as u64)),435        "active data exceeds __data_end"436    );437    ensure!(438        global("__stack_pointer", true)? == STACK_SIZE,439        "stack pointer does not match profile"440    );441    let startup = |name: &str| -> Result<u32> {442        let e = export(name)?;443        ensure!(e.kind == ExternalKind::Func, "{name} must be a function");444        ensure!(445            (e.index as usize) >= imported.len(),446            "startup must be a defined function"447        );448        let ty = &types[functions[e.index as usize - imported.len()] as usize];449        ensure!(450            ty.params().is_empty() && ty.results().is_empty(),451            "{name} must have signature () -> ()"452        );453        Ok(e.index)454    };455    let original_init = startup("canister_init")?;456    let original_upgrade = startup("canister_post_upgrade")?;457    // KEEP with skip_pre_upgrade must fail the clean-marker check.458    startup("canister_pre_upgrade")?;459    let e = export(ABI_ADMIT_EXPORT)?;460    ensure!(461        e.kind == ExternalKind::Func && e.index as usize >= imported.len(),462        "{ABI_ADMIT_EXPORT} must be a defined function"463    );464    let ty = &types[functions[e.index as usize - imported.len()] as usize];465    ensure!(466        ty.params() == [ValType::I32] && ty.results() == [ValType::I32],467        "{ABI_ADMIT_EXPORT} must have signature (i32) -> i32"468    );469    let abi_admit = e.index;470    let void_type = u32::try_from(types.len())?;471    let initializer = u32::try_from(imported.len() + functions.len())?;472    let mut new_types = enc::TypeSection::new();473    for ty in &types {474        let params = ty475            .params()476            .iter()477            .copied()478            .map(enc::ValType::try_from)479            .collect::<std::result::Result<Vec<_>, _>>()?;480        let results = ty481            .results()482            .iter()483            .copied()484            .map(enc::ValType::try_from)485            .collect::<std::result::Result<Vec<_>, _>>()?;486        new_types.ty().function(params, results);487    }488    new_types.ty().function([], []);489    let mut new_functions = enc::FunctionSection::new();490    for index in &functions {491        new_functions.function(*index);492    }493    for _ in 0..3 {494        new_functions.function(void_type);495    }496    let mut new_exports = enc::ExportSection::new();497    for e in &exports {498        if e.name == ABI_ADMIT_EXPORT {499            continue;500        }501        let index = match e.name {502            "canister_init" => initializer + 1,503            "canister_post_upgrade" => initializer + 2,504            _ => e.index,505        };506        let kind = match e.kind {507            ExternalKind::Func => enc::ExportKind::Func,508            ExternalKind::Table => enc::ExportKind::Table,509            ExternalKind::Memory => enc::ExportKind::Memory,510            ExternalKind::Global => enc::ExportKind::Global,511            _ => bail!("unsupported export kind"),512        };513        new_exports.export(e.name, kind, index);514    }515    let mut new_data = enc::DataSection::new();516    for bytes in &data {517        new_data.passive(bytes.iter().copied());518    }519    let mut new_code = enc::CodeSection::new();520    for range in &bodies {521        new_code.raw(&raw[range.start as usize..range.end as usize]);522    }523    // Reset the private SDK-control gap and current statics, including BSS,524    // then replay initialized data. No initializer may occupy the control gap. The525    // new instance supplies fresh globals (including its stack pointer). Rust526    // initializes stack values before reading them, so old stack bytes and the527    // unused static tail do not need clearing. Runtime payloads remain528    // unreachable after allocator ownership recovery.529    let mut reset = enc::Function::new([]);530    let reset_bytes = data_end - STACK_SIZE;531    if reset_bytes != 0 {532        reset533            .instruction(&address(memory_profile, STACK_SIZE)?)534            .instruction(&enc::Instruction::I32Const(0))535            .instruction(&address(memory_profile, reset_bytes)?)536            .instruction(&enc::Instruction::MemoryFill(0));537    }538    for &(index, offset, len) in &copies {539        reset540            .instruction(&address(memory_profile, offset)?)541            .instruction(&enc::Instruction::I32Const(0))542            .instruction(&enc::Instruction::I32Const(len as i32))543            .instruction(&enc::Instruction::MemoryInit {544                mem: 0,545                data_index: index,546            })547            .instruction(&enc::Instruction::DataDrop(index));548    }549    reset.instruction(&enc::Instruction::End);550    new_code.function(&reset);551    for (is_upgrade, original) in [(false, original_init), (true, original_upgrade)] {552        let mut wrapper = enc::Function::new([]);553        if is_upgrade {554            guard_bootstrap(&mut wrapper, memory_profile)?;555            guard_clean_shutdown(&mut wrapper, memory_profile)?;556        }557        wrapper.instruction(&enc::Instruction::Call(initializer));558        wrapper559            .instruction(&enc::Instruction::I32Const(i32::from(is_upgrade)))560            .instruction(&enc::Instruction::Call(abi_admit))561            .instruction(&enc::Instruction::I32Const(1))562            .instruction(&enc::Instruction::I32Ne)563            .instruction(&enc::Instruction::If(enc::BlockType::Empty))564            .instruction(&enc::Instruction::Unreachable)565            .instruction(&enc::Instruction::End);566        wrapper567            .instruction(&enc::Instruction::Call(original))568            .instruction(&enc::Instruction::End);569        new_code.function(&wrapper);570    }571    let manifest = json!({"profile":format!("cdk-rsx-shared-pages-wasm{}-v2", memory_profile.pointer_width()),572        "memory64":memory_profile == MemoryProfile::Wasm64, "pointer_width":memory_profile.pointer_width(),573        "stack_bytes":STACK_SIZE,"hot_control_base":profile::HOT_CONTROL_BASE,574        "hot_control_bytes":profile::HOT_CONTROL_BYTES,"static_data_base":profile::STATIC_DATA_BASE,"static_limit":STATIC_LIMIT,"control_base":profile::CONTROL_BASE,575        "page_size":profile::WASM_PAGE,"address_limit":memory_profile.address_limit(),576        "initial_memory_bytes":initial_memory,577        "heap_base":heap_base,"active_data_segments":copies.len(),"startup":"guard-bootstrap-then-passive-reinitialize-statics",578        "data_end":data_end,"startup_reset_offset":STACK_SIZE,"startup_reset_bytes":reset_bytes,579        "platform_format":memory_profile.platform_format(),"bootstrap_address":profile::BOOTSTRAP_BASE,580        "upgrade_option":"wasm_memory_persistence=keep", "validator":"cdk-rsx-wasm/0.1.0 wasmparser/0.262.0",581        "raw_methods":raw_methods(raw)?});582    let mut manifest = manifest;583    manifest["startup"] =584        json!("guard-bootstrap-and-clean-then-static-replay-then-catalog-admission");585    manifest["typed_root"] = json!({586        "contract": "cdk-rsx-closed-catalog-v1",587        "handoff_policy": "quiescent-owners-runtime-recovery-v1",588        "clean_marker_address": profile::BOOTSTRAP_BASE + profile::ROOT_CLEAN_MARKER_OFFSET,589        "clean_marker_magic": profile::ROOT_CLEAN_MARKER_MAGIC,590        "saved_catalog_address": profile::BOOTSTRAP_BASE + profile::ROOT_CATALOG_OFFSET,591        "admission_hook": ABI_ADMIT_EXPORT,592        "digest_check": "after-new-static-replay-before-retained-pointers",593        "target_publication": "root-lifecycle-after-successful-conversion"594    });595    let mut out = enc::Module::new();596    let mut emitted_data = false;597    for (id, range) in sections {598        match id {599            1 => {600                out.section(&new_types);601            }602            3 => {603                out.section(&new_functions);604            }605            7 => {606                out.section(&new_exports);607            }608            10 => {609                out.section(&enc::DataCountSection {610                    count: u32::try_from(data.len())?,611                });612                out.section(&new_code);613            }614            11 => {615                out.section(&new_data);616                emitted_data = true;617            }618            12 => {}619            _ => {620                out.section(&enc::RawSection {621                    id,622                    data: &raw[range.start as usize..range.end as usize],623                });624            }625        }626    }627    if !emitted_data {628        out.section(&new_data);629    }630    out.section(&enc::CustomSection {631        name: EOP_NAME.into(),632        data: (&[1][..]).into(),633    });634    out.section(&enc::CustomSection {635        name: PROFILE_NAME.into(),636        data: serde_json::to_vec(&manifest)?.into(),637    });638    if let Some(did) = wire {639        ensure!(!did.trim().is_empty(), "empty Wire interface");640        let interface: Value = serde_json::from_str(did)?;641        out.section(&enc::CustomSection {642            name: WIRE_NAME.into(),643            data: serde_json::to_vec(&interface)?.into(),644        });645    }646    let out = out.finish();647    Validator::new_with_features(features())648        .validate_all(&out)649        .context("transformed module failed validation")?;650    if let Some(did) = wire {651        check_wire(&out, did.as_bytes())?;652    }653    Ok((out, manifest))654}655656/// Runs without Rust statics, allocator, data segments, or runtime services.657/// The IC rolls back a rejected upgrade; this establishes the physical contract658/// before startup is allowed to interpret the retained image. Typed roots perform659/// their additional compiled catalog check after new static replay, before any660/// retained allocator/module pointer is opened.661fn guard_bootstrap(body: &mut enc::Function, profile: MemoryProfile) -> Result<()> {662    fn reject_if(body: &mut enc::Function) {663        body.instruction(&enc::Instruction::If(enc::BlockType::Empty))664            .instruction(&enc::Instruction::Unreachable)665            .instruction(&enc::Instruction::End);666    }667    fn load(668        body: &mut enc::Function,669        profile: MemoryProfile,670        base: usize,671        offset: usize,672    ) -> Result<()> {673        body.instruction(&address(profile, base as u64)?)674            .instruction(&enc::Instruction::I64Load(enc::MemArg {675                offset: offset as u64,676                align: 3,677                memory_index: 0,678            }));679        Ok(())680    }681    fn expect(682        body: &mut enc::Function,683        profile: MemoryProfile,684        base: usize,685        offset: usize,686        expected: u64,687    ) -> Result<()> {688        load(body, profile, base, offset)?;689        body.instruction(&enc::Instruction::I64Const(expected as i64))690            .instruction(&enc::Instruction::I64Ne);691        reject_if(body);692        Ok(())693    }694    fn complementary(695        body: &mut enc::Function,696        profile: MemoryProfile,697        base: usize,698        offset: usize,699    ) -> Result<()> {700        load(body, profile, base, offset)?;701        load(body, profile, base, offset + 8)?;702        body.instruction(&enc::Instruction::I64Xor)703            .instruction(&enc::Instruction::I64Const(-1))704            .instruction(&enc::Instruction::I64Ne);705        reject_if(body);706        Ok(())707    }708    let bootstrap_pages = 1;709    let minimum = profile::BOOTSTRAP_BASE / profile::WASM_PAGE + bootstrap_pages;710    memory_size_u64(body, profile);711    body.instruction(&enc::Instruction::I64Const(minimum as i64))712        .instruction(&enc::Instruction::I64LtU);713    reject_if(body);714    memory_size_u64(body, profile);715    body.instruction(&enc::Instruction::I64Const(716        (profile.address_limit() / profile::WASM_PAGE as u64) as i64,717    ))718    .instruction(&enc::Instruction::I64GtU);719    reject_if(body);720    // Admit only this geometry. Anchor and provider facts are checked together721    // before any reset or Rust call; a payload resembling an anchor is insufficient.722    for (offset, expected) in profile.anchor_words() {723        expect(body, profile, profile::BOOTSTRAP_BASE, offset, expected)?;724    }725    for (offset, expected) in profile.provider_words() {726        expect(body, profile, profile::PROVIDER_HEADER, offset, expected)?;727    }728    expect(729        body,730        profile,731        profile::CONTROL_BASE,732        512,733        profile::BOOTSTRAP_PAGE as u64,734    )?;735    expect(736        body,737        profile,738        profile::CONTROL_BASE,739        520,740        bootstrap_pages as u64,741    )?;742    expect(body, profile, profile::PROVIDER_HEADER, 16, 1)?;743    expect(body, profile, profile::PROVIDER_HEADER, 24, !1)?;744    complementary(body, profile, profile::PROVIDER_HEADER, 0)?;745    load(body, profile, profile::PROVIDER_HEADER, 0)?;746    memory_size_u64(body, profile);747    body.instruction(&enc::Instruction::I64Const(748        (profile::CONTROL_BASE / profile::WASM_PAGE) as i64,749    ))750    .instruction(&enc::Instruction::I64Sub)751    .instruction(&enc::Instruction::I64Ne);752    reject_if(body);753    complementary(body, profile, profile::BOOTSTRAP_BASE, 16)?;754    load(body, profile, profile::BOOTSTRAP_BASE, 16)?;755    body.instruction(&enc::Instruction::I64Const(756        profile::STORE_ROOT_BYTES as i64,757    ))758    .instruction(&enc::Instruction::I64LtU);759    reject_if(body);760    load(body, profile, profile::BOOTSTRAP_BASE, 16)?;761    memory_size_u64(body, profile);762    body.instruction(&enc::Instruction::I64Const(profile::WASM_PAGE as i64))763        .instruction(&enc::Instruction::I64Mul)764        .instruction(&enc::Instruction::I64Const(profile::CONTROL_BASE as i64))765        .instruction(&enc::Instruction::I64Sub)766        .instruction(&enc::Instruction::I64GtU);767    reject_if(body);768    Ok(())769}770771/// Fixed-format check only: no Rust/global/static/allocator access before replay.772fn guard_clean_shutdown(body: &mut enc::Function, profile: MemoryProfile) -> Result<()> {773    let marker = address(774        profile,775        (profile::BOOTSTRAP_BASE + profile::ROOT_CLEAN_MARKER_OFFSET) as u64,776    )?;777    body.instruction(&marker)778        .instruction(&enc::Instruction::I64Load(enc::MemArg {779            offset: 0,780            align: 3,781            memory_index: 0,782        }))783        .instruction(&enc::Instruction::I64Const(784            profile::ROOT_CLEAN_MARKER_MAGIC as i64,785        ))786        .instruction(&enc::Instruction::I64Ne)787        .instruction(&enc::Instruction::If(enc::BlockType::Empty))788        .instruction(&enc::Instruction::Unreachable)789        .instruction(&enc::Instruction::End)790        // A successful KEEP consumes the preparation independently of the original791        // lifecycle's SDK macros. A rejected install restores it with IC rollback.792        .instruction(&marker)793        .instruction(&enc::Instruction::I64Const(0))794        .instruction(&enc::Instruction::I64Store(enc::MemArg {795            offset: 0,796            align: 3,797            memory_index: 0,798        }));799    Ok(())800}801802/// Read compiler-emitted raw endpoint metadata. Each declaration must still803/// match an actual callable export and must never also appear in public Wire interface.804pub fn raw_methods(raw: &[u8]) -> Result<std::collections::BTreeMap<String, String>> {805    let mut methods = std::collections::BTreeMap::new();806    for payload in Parser::new(0).parse_all(raw) {807        if let Payload::CustomSection(section) = payload? {808            if section.name() != RAW_METHODS_NAME {809                continue;810            }811            let text =812                std::str::from_utf8(section.data()).context("invalid raw method metadata")?;813            ensure!(text.ends_with('\n'), "unterminated raw method metadata");814            for line in text.lines() {815                let (mode, name) = line816                    .split_once('\t')817                    .context("invalid raw method declaration")?;818                ensure!(819                    matches!(mode, "query" | "update" | "composite_query"),820                    "invalid raw method mode"821                );822                ensure!(823                    !name.is_empty() && !name.contains(['\t', '\r']),824                    "invalid raw method name"825                );826                ensure!(827                    methods.insert(name.to_owned(), mode.to_owned()).is_none(),828                    "duplicate raw method declaration {name}"829                );830            }831        }832    }833    Ok(methods)834}835836/// Parse and validate the generated host-only Wire interface.837pub fn wire_interface(bytes: &[u8]) -> Result<Value> {838    let value: Value = serde_json::from_slice(bytes)?;839    ensure!(840        value["format"] == "cdk-rsx-wire-v1" && value["encoding"] == "postcard",841        "unsupported Wire interface format"842    );843    let types: std::collections::BTreeMap<String, Value> =844        serde_json::from_value(value["types"].clone())?;845    let methods = value["methods"]846        .as_array()847        .context("Wire methods must be an array")?;848    cdk_rsx_wire::typescript::generate_method_registry(849        &types,850        methods,851        "./wire-runtime.mjs",852        &Default::default(),853        |report| eprint!("{report}"),854    )855    .map_err(|e| anyhow::anyhow!("invalid Wire schema: {e:?}"))?;856    let validate_limits = |m: &Value, side: &str| -> Result<()> {857        let get = |suffix: &str| -> Result<u64> {858            let value = m[format!("{side}{suffix}")]859                .as_u64()860                .context("Wire resource limit")?;861            ensure!(862                value <= (1u64 << 53) - 1,863                "Wire resource limit exceeds JavaScript integer range"864            );865            Ok(value)866        };867        let bytes = get("Bytes")?;868        ensure!(869            bytes > 0 && get("Allocation")? >= bytes && get("Nodes")? > 0 && get("Depth")? > 0,870            "invalid Wire limits"871        );872        Ok(())873    };874    for m in methods {875        for side in ["request", "response"] {876            validate_limits(m, side)?;877        }878    }879    if !value["constructor"].is_null() {880        let constructor = &value["constructor"];881        ensure!(882            constructor.is_object(),883            "Wire constructor must be an object or null"884        );885        validate_limits(constructor, "request")?;886        ensure!(887            constructor["request"]["k"] == "extension-tuple"888                && constructor["request"]["items"]889                    .as_array()890                    .is_some_and(|items| items.len() == 1),891            "Wire constructor requires one logical argument tuple inside a sparse root"892        );893        cdk_rsx_wire::typescript::validate_payload_schema(&types, &constructor["request"])894            .map_err(|e| anyhow::anyhow!("invalid Wire constructor: {e:?}"))?;895    }896    Ok(value)897}898899/// Emit the schema-derived TypeScript codec module. Runtime code is shared.900pub fn wire_bindings(bytes: &[u8]) -> Result<String> {901    wire_bindings_with_runtime(bytes, "./wire-runtime.mjs")902}903904/// Emit bindings with the selected runtime import, preserving all schema labels.905pub fn wire_bindings_with_runtime(bytes: &[u8], runtime_module: &str) -> Result<String> {906    let value = wire_interface(bytes)?;907    let types = serde_json::from_value(value["types"].clone())?;908    cdk_rsx_wire::typescript::generate_method_registry(909        &types,910        value["methods"].as_array().unwrap(),911        runtime_module,912        &Default::default(),913        |report| eprint!("{report}"),914    )915    .map_err(|e| anyhow::anyhow!("invalid Wire schema: {e:?}"))916}917918pub fn check_wire(raw: &[u8], expected: &[u8]) -> Result<()> {919    check_wire_inner(raw, expected, false)920}921922fn check_wire_inner(raw: &[u8], expected: &[u8], allow_pending_profile: bool) -> Result<()> {923    if !allow_pending_profile {924        page_profile::check_final(raw)?;925    }926    Validator::new_with_features(features()).validate_all(raw)?;927    let interface = wire_interface(expected)?;928    let mut declared = std::collections::BTreeMap::new();929    for method in interface["methods"].as_array().unwrap() {930        let name = method["name"].as_str().context("method name")?;931        let mode = method["mode"].as_str().context("method mode")?;932        ensure!(933            !name.starts_with("<cdk-rsx internal>"),934            "reserved SDK method cannot appear in public Wire interface"935        );936        ensure!(937            declared.insert(name.to_owned(), mode.to_owned()).is_none(),938            "duplicate Wire method {name}"939        );940    }941    for (name, mode) in raw_methods(raw)? {942        ensure!(943            !declared.contains_key(&name),944            "raw method {name} must not appear in public Wire interface"945        );946        declared.insert(name, mode);947    }948    let mut exported = std::collections::BTreeMap::new();949    let mut found = 0;950    for p in Parser::new(0).parse_all(raw) {951        match p? {952            Payload::CustomSection(s) if s.name() == WIRE_NAME => {953                ensure!(954                    serde_json::from_slice::<Value>(s.data())? == interface,955                    "Wire metadata differs from generated interface"956                );957                found += 1;958            }959            Payload::CustomSection(s)960                if matches!(961                    s.name(),962                    "icp:private candid:service" | "icp:public candid:service"963                ) =>964            {965                bail!("Candid metadata is not supported")966            }967            Payload::ExportSection(reader) => {968                for e in reader {969                    let e = e?;970                    ensure!(971                        e.name != "canister_query __get_candid_interface_tmp_hack",972                        "obsolete Candid discovery export"973                    );974                    for mode in ["query", "update", "composite_query"] {975                        if let Some(name) = e.name.strip_prefix(&format!("canister_{mode} ")) {976                            ensure!(977                                exported.insert(name.to_owned(), mode.to_owned()).is_none(),978                                "duplicate method export {name}"979                            );980                        }981                    }982                }983            }984            _ => {}985        }986    }987    ensure!(988        found == 1,989        "expected exactly one public Wire interface section"990    );991    ensure!(992        declared == exported,993        "public Wire interface plus raw methods/modes differ from Wasm exports: declared {declared:?}, exported {exported:?}"994    );995    Ok(())996}997998/// Count emitted vector operators, for build comparisons rather than runtime dispatch.999pub fn inspect(raw: &[u8]) -> Result<Value> {1000    page_profile::check_final(raw)?;1001    Validator::new_with_features(features()).validate_all(raw)?;1002    let profile = memory_profile(raw)?;1003    let mut simd = 0;1004    let mut total = 0;1005    for p in Parser::new(0).parse_all(raw) {1006        if let Payload::CodeSectionEntry(body) = p? {1007            let mut reader = body.get_operators_reader()?;1008            while !reader.eof() {1009                let offset = reader.original_position() as usize;1010                reader.read()?;1011                total += 1;1012                // The validated 0xfd opcode prefix identifies SIMD operators.1013                if raw[offset] == 0xfd {1014                    simd += 1;1015                }1016            }1017        }1018    }1019    Ok(1020        json!({"bytes":raw.len(),"operators":total,"simd_operators":simd,"raw_methods":raw_methods(raw)?,1021            "memory64":profile == MemoryProfile::Wasm64,"pointer_width":profile.pointer_width()}),1022    )1023}10241025#[cfg(test)]1026mod profile_tests {1027    use super::*;10281029    #[test]1030    fn memory32_constants_preserve_unsigned_bits_and_reject_narrowing_overflow() {1031        let raw = wat::parse_str("(module (global i32 (i32.const -1)))").unwrap();1032        for payload in Parser::new(0).parse_all(&raw) {1033            if let Payload::GlobalSection(globals) = payload.unwrap() {1034                let global = globals.into_iter().next().unwrap().unwrap();1035                assert_eq!(1036                    constant(global.init_expr, MemoryProfile::Wasm32).unwrap(),1037                    u32::MAX as u641038                );1039            }1040        }1041        assert!(matches!(1042            address(MemoryProfile::Wasm32, u32::MAX as u64).unwrap(),1043            enc::Instruction::I32Const(-1)1044        ));1045        assert!(address(MemoryProfile::Wasm32, 1u64 << 32).is_err());1046    }1047}