From 20b4dc8af3d38e0e784fa8ef380108c054aade22 Mon Sep 17 00:00:00 2001 From: Mohanson Date: Tue, 26 Mar 2024 14:36:28 +0800 Subject: [PATCH] Backport #424 --- fuzz/Cargo.toml | 6 ++++ fuzz/fuzz_targets/snapshot.rs | 55 +++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 fuzz/fuzz_targets/snapshot.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index fcee6175..3092e404 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -43,3 +43,9 @@ name = "isa_b" path = "fuzz_targets/isa_b.rs" test = false doc = false + +[[bin]] +name = "snapshot" +path = "fuzz_targets/snapshot.rs" +test = false +doc = false diff --git a/fuzz/fuzz_targets/snapshot.rs b/fuzz/fuzz_targets/snapshot.rs new file mode 100644 index 00000000..c1b98565 --- /dev/null +++ b/fuzz/fuzz_targets/snapshot.rs @@ -0,0 +1,55 @@ +#![no_main] +use ckb_vm::cost_model::constant_cycles; +use ckb_vm::machine::asm::{AsmCoreMachine, AsmMachine}; +use ckb_vm::machine::{DefaultMachineBuilder, VERSION2}; +use ckb_vm::snapshot; +use ckb_vm::{Bytes, Error, SupportMachine, ISA_A, ISA_B, ISA_IMC, ISA_MOP}; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let mut machine1 = { + let asm_core = AsmCoreMachine::new(ISA_IMC | ISA_A | ISA_B | ISA_MOP, VERSION2, 200_000); + let machine = DefaultMachineBuilder::>::new(asm_core) + .instruction_cycle_func(Box::new(constant_cycles)) + .build(); + AsmMachine::new(machine) + }; + let program = Bytes::copy_from_slice(data); + if machine1.load_program(&program, &[]).is_err() { + return; + }; + let result1 = machine1.run(); + if machine1.machine.cycles() < 4 { + return; + } + + let half_cycles = machine1.machine.cycles() / 2; + let mut machine2 = { + let asm_core = + AsmCoreMachine::new(ISA_IMC | ISA_A | ISA_B | ISA_MOP, VERSION2, half_cycles); + let machine = DefaultMachineBuilder::>::new(asm_core) + .instruction_cycle_func(Box::new(constant_cycles)) + .build(); + AsmMachine::new(machine) + }; + machine2.load_program(&program, &[]).unwrap(); + let result2 = machine2.run(); + assert_eq!(result2.unwrap_err(), Error::CyclesExceeded); + let snap = snapshot::make_snapshot(&mut machine2.machine).unwrap(); + + let mut machine3 = { + let asm_core = + AsmCoreMachine::new(ISA_IMC | ISA_A | ISA_B | ISA_MOP, VERSION2, half_cycles); + let machine = DefaultMachineBuilder::>::new(asm_core) + .instruction_cycle_func(Box::new(constant_cycles)) + .build(); + AsmMachine::new(machine) + }; + snapshot::resume(&mut machine3.machine, &snap).unwrap(); + + machine3.machine.set_cycles(machine2.machine.cycles()); + machine3.machine.set_max_cycles(200_000); + let result3 = machine3.run(); + assert_eq!(result1, result3); + assert_eq!(machine1.machine.cycles(), machine3.machine.cycles()); +});