wrappers.rs

verification/proofs/startup-admission/native/wrappers.rs

wrappers.rs88 lines← SDK documentation
1//! Actual transform output, exercised with controlled operational callees.2use cdk_rsx_platform::profile::{self,MemoryProfile};3use std::{fs,path::Path,convert::Infallible};4use wasm_encoder::{self as enc,reencode::Reencode};5use wasmparser::{Parser,Payload,Operator};67struct Mutation { current:usize, target:usize, kind:&'static str, changed:usize }8impl Reencode for Mutation {9    type Error=Infallible;10    fn parse_function_body(&mut self,code:&mut enc::CodeSection,body:wasmparser::FunctionBody<'_>)->Result<(),enc::reencode::Error<Self::Error>> {11        let selected=self.current==self.target;self.current+=1;12        if !selected { return enc::reencode::utils::parse_function_body(self,code,body) }13        let mut function=self.new_function_with_parsed_locals(&body)?;14        let mut ops=body.get_operators_reader()?.into_iter().collect::<Result<Vec<_>,_>>()?;15        if self.kind=="guard" {16            for op in &mut ops { if matches!(op,Operator::I32Ne) { *op=Operator::I32Eq;self.changed+=1; } }17        } else {18            let calls=ops.iter().enumerate().filter_map(|(i,op)|match op {Operator::Call{function_index}=>Some((i,*function_index)),_=>None}).collect::<Vec<_>>();19            assert_eq!(calls.len(),3,"wrapper reset/admission/original call inventory");20            let (last,original)=calls[2];ops.remove(last);ops.insert(calls[0].0+1,Operator::Call{function_index:original});self.changed+=1;21        }22        for op in ops { function.instruction(&self.instruction(op)?); }23        code.function(&function);Ok(())24    }25}2627pub fn emit(out:&Path) {28    let mut metadata=vec![];29    for width in [32,64] {30        let p=if width==32 {MemoryProfile::Wasm32}else{MemoryProfile::Wasm64};31        let pages=profile::INITIAL_MEMORY/profile::WASM_PAGE;32        let maximum=p.address_limit()/profile::WASM_PAGE as u64;33        let mem=if width==32 {"memory (export \"memory\")"}else{"memory (export \"memory\") i64"};34        let data=profile::STATIC_DATA_BASE;35        let trace=profile::CONTROL_BASE+profile::WASM_PAGE;36        let wat=format!(r#"(module37          ({mem} {pages} {maximum})38          (global (export "__stack_pointer") (mut i{width}) (i{width}.const {stack}))39          (global (export "__heap_base") i{width} (i{width}.const {end}))40          (global (export "__data_end") i{width} (i{width}.const {end}))41          (func $event (param i32)42            i{width}.const {trace} i{width}.const {trace} i32.load i32.const 10 i32.mul local.get 0 i32.add i32.store)43          (func (export "canister_init") i32.const 2 call $event call $publish)44          (func (export "canister_pre_upgrade"))45          (func (export "canister_post_upgrade")46            i32.const 3 call $event47            i{width}.const {fail} i32.load if unreachable end call $publish)48          (func (export "__cdk_rsx_memory_abi_admit") (param i32) (result i32)49            i{width}.const {mode} local.get 0 i32.store50            i32.const 1 call $event51            i{width}.const {data} i32.load i32.const 1953719668 i32.ne if unreachable end52            i{width}.const {bss} i64.load i64.const 0 i64.ne if unreachable end53            i{width}.const {stack} i64.load i64.const 0 i64.ne if unreachable end54            i{width}.const {accept} i32.load)55          (func $publish56            i32.const 4 call $event i{width}.const {publication} i64.const 1234 i64.store)57          (data (i{width}.const {data}) "test"))"#,58            stack=profile::STACK_SIZE,end=data+16,fail=trace+8,mode=trace+12,bss=data+8,accept=trace+4,publication=trace+16);59        let raw=wat::parse_str(&wat).unwrap();60        let (emitted,manifest)=cdk_rsx_wasm::transform(&raw,None).unwrap();61        let prefix=format!("wrapper{width}");62        fs::write(out.join(format!("{prefix}.raw.wasm")),&raw).unwrap();63        fs::write(out.join(format!("{prefix}.wasm")),&emitted).unwrap();64        let target=Parser::new(0).parse_all(&emitted).find_map(|p|match p.unwrap() {65            Payload::ExportSection(exports)=>exports.into_iter().map(Result::unwrap).find(|e|e.name=="canister_post_upgrade").map(|e|e.index as usize),_=>None }).unwrap();66        for kind in ["guard","reorder"] {67            let mut mutation=Mutation{current:0,target,kind,changed:0};let mut module=enc::Module::new();68            mutation.parse_core_module(&mut module,Parser::new(0),&emitted).unwrap();assert_eq!(mutation.changed,1);69            let bytes=module.finish();wasmparser::Validator::new_with_features(cdk_rsx_wasm::features()).validate_all(&bytes).unwrap();70            fs::write(out.join(format!("{prefix}-{kind}.wasm")),bytes).unwrap();71        }72        let mut words=p.anchor_words().into_iter().map(|(o,v)|(profile::BOOTSTRAP_BASE+o,v.to_string())).collect::<Vec<_>>();73        words.extend(p.provider_words().into_iter().map(|(o,v)|(profile::PROVIDER_HEADER+o,v.to_string())));74        let committed=pages-profile::CONTROL_BASE/profile::WASM_PAGE;75        words.extend([76            (profile::BOOTSTRAP_BASE+16,profile::STORE_ROOT_BYTES as u64),77            (profile::BOOTSTRAP_BASE+24,!(profile::STORE_ROOT_BYTES as u64)),78            (profile::PROVIDER_HEADER,committed as u64),(profile::PROVIDER_HEADER+8,!(committed as u64)),79            (profile::PROVIDER_HEADER+16,1),(profile::PROVIDER_HEADER+24,!1),80            (profile::CONTROL_BASE+512,profile::BOOTSTRAP_PAGE as u64),(profile::CONTROL_BASE+520,1),81        ].map(|(a,v)|(a,v.to_string())));82        metadata.push(serde_json::json!({"width":width,"prefix":prefix,"manifest":manifest,"words":words,83            "trace":trace,"static":data,"stack":profile::STACK_SIZE,84            "marker":profile::BOOTSTRAP_BASE+profile::ROOT_CLEAN_MARKER_OFFSET,"magic":profile::ROOT_CLEAN_MARKER_MAGIC.to_string(),85            "format":profile::BOOTSTRAP_BASE+56}));86    }87    fs::write(out.join("wrappers.json"),serde_json::to_vec_pretty(&metadata).unwrap()).unwrap();88}