tsffs/interfaces/fuzz.rs
1// Copyright (C) 2024 Intel Corporation
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{
5 state::{SolutionKind, StopReason},
6 util::c_str_arg,
7 ManualStartAddress, ManualStartInfo, ManualStartSize, Tsffs,
8};
9use anyhow::{anyhow, Result};
10use libafl::inputs::HasBytesVec;
11use simics::{debug, interface, lookup_file, AsConfObject, AttrValue, ConfObject, GenericAddress};
12use std::{ffi::c_char, fs::read};
13
14extern crate ffi2 as ffi;
15
16#[interface(name = "fuzz")]
17impl Tsffs {
18 /// Reproduce a test case execution. This will set the fuzzer's next input through
19 /// one execution using the provided file as input instead of taking input from the
20 /// fuzzer. It will stop execution at the first stop, timeout, or other solution
21 /// instead of continuing the fuzzing loop.
22 ///
23 /// This can be called during configuration *or* after stopping the fuzzer once a solution
24 /// has been found.
25 pub fn repro(&mut self, testcase_file: *mut c_char) -> Result<()> {
26 // SAFETY: Simics passes NULL or a NUL-terminated string valid for this call
27 let simics_path = unsafe { c_str_arg(testcase_file, "testcase_file") }?;
28
29 let testcase_file = lookup_file(&simics_path)?;
30
31 debug!(self.as_conf_object(), "repro({})", testcase_file.display());
32
33 let contents = read(&testcase_file).map_err(|e| {
34 anyhow!(
35 "Failed to read repro testcase file {}: {}",
36 testcase_file.display(),
37 e
38 )
39 })?;
40
41 self.repro_testcase = Some(contents);
42
43 if self.iterations > 0 {
44 // We've done an iteration already, so we need to reset and run
45 self.restore_initial_snapshot()?;
46 self.get_and_write_testcase()?;
47 self.post_timeout_event()?;
48 self.continue_after_repro_prepared()?;
49 }
50
51 Ok(())
52 }
53
54 /// Interface method to manually start the fuzzing loop by taking a snapshot, saving the
55 /// testcase and size address and resuming execution of the simulation. This method does
56 /// not need to be called if `set_start_on_harness` is enabled.
57 ///
58 /// # Arguments
59 ///
60 /// * `cpu` - The CPU whose memory space should be written
61 /// * `testcase_address` - The address to write test cases to
62 /// * `size_address` - The address to write the size of each test case to (optional,
63 /// `max_size` must be given if not provided).
64 ///
65 /// If your target cannot take advantage of the written-back size pointer, use
66 /// `start_with_max_size` instead.
67 pub fn start_with_buffer_ptr_size_ptr(
68 &mut self,
69 cpu: *mut ConfObject,
70 buffer_address: GenericAddress,
71 size_address: GenericAddress,
72 virt: bool,
73 ) -> Result<()> {
74 debug!(
75 self.as_conf_object(),
76 "start({buffer_address:#x}, {size_address:#x})"
77 );
78
79 self.stop_simulation(StopReason::ManualStart {
80 processor: cpu,
81 info: ManualStartInfo {
82 address: if virt {
83 ManualStartAddress::Virtual(buffer_address)
84 } else {
85 ManualStartAddress::Physical(buffer_address)
86 },
87 size: ManualStartSize::SizePtr {
88 address: if virt {
89 ManualStartAddress::Virtual(size_address)
90 } else {
91 ManualStartAddress::Physical(size_address)
92 },
93 },
94 },
95 })?;
96
97 Ok(())
98 }
99
100 /// Interface method to manually start the fuzzing loop by taking a snapshot, saving
101 /// the testcase and maximum testcase size and resuming execution of the simulation.
102 /// This method does not need to be called if `set_start_on_harness` is enabled.
103 ///
104 /// # Arguments
105 ///
106 /// * `cpu` - The CPU whose memory space should be written
107 /// * `testcase_address` - The address to write test cases to
108 /// * `maximum_size` - The maximum size of the test case. The actual size of each test case will
109 /// not be written back to the target software
110 ///
111 /// If your target does not have a buffer readily available to receive testcase data or
112 /// you simply want to use it directly in some other way (e.g. by sending it to a network
113 /// port), use `start_without_buffer`
114 pub fn start_with_buffer_ptr_size_value(
115 &mut self,
116 cpu: *mut ConfObject,
117 testcase_address: GenericAddress,
118 maximum_size: u32,
119 virt: bool,
120 ) -> Result<()> {
121 debug!(
122 self.as_conf_object(),
123 "start_with_maximum_size({testcase_address:#x}, {maximum_size:#x})"
124 );
125
126 self.stop_simulation(StopReason::ManualStart {
127 processor: cpu,
128 info: ManualStartInfo {
129 address: if virt {
130 ManualStartAddress::Virtual(testcase_address)
131 } else {
132 ManualStartAddress::Physical(testcase_address)
133 },
134 size: ManualStartSize::MaxSize(maximum_size.try_into()?),
135 },
136 })?;
137
138 Ok(())
139 }
140
141 /// Interface method to manually start the fuzzing loop by taking a snapshot, saving
142 /// the testcase, size address, and maximum testcase size and resuming execution of the
143 /// simulation. This method does not need to be called if `set_start_on_harness` is enabled.
144 ///
145 /// # Arguments
146 ///
147 /// * `cpu` - The CPU whose memory space should be written
148 /// * `testcase_address` - The address to write test cases to
149 /// * `size_address` - The address to write the size of each test case to
150 /// * `maximum_size` - The maximum size of the test case. The actual size of each test case will
151 /// be written back to the target software at the provided size address.
152 ///
153 /// If your target cannot take advantage of the written-back size pointer, use
154 /// `start_with_max_size` instead.
155 pub fn start_with_buffer_ptr_size_ptr_value(
156 &mut self,
157 cpu: *mut ConfObject,
158 buffer_address: GenericAddress,
159 size_address: GenericAddress,
160 maximum_size: u32,
161 virt: bool,
162 ) -> Result<()> {
163 debug!(
164 self.as_conf_object(),
165 "start({buffer_address:#x}, {size_address:#x}, {maximum_size:#x})"
166 );
167
168 self.stop_simulation(StopReason::ManualStart {
169 processor: cpu,
170 info: ManualStartInfo {
171 address: if virt {
172 ManualStartAddress::Virtual(buffer_address)
173 } else {
174 ManualStartAddress::Physical(buffer_address)
175 },
176 size: ManualStartSize::SizePtrAndMaxSize {
177 address: if virt {
178 ManualStartAddress::Virtual(size_address)
179 } else {
180 ManualStartAddress::Physical(size_address)
181 },
182 maximum_size: maximum_size.try_into()?,
183 },
184 },
185 })?;
186
187 Ok(())
188 }
189
190 /// Interface method to manually start the fuzzing loop by taking a snapshot, saving
191 /// the testcase and maximum testcase size and resuming execution of the simulation.
192 /// This method does not need to be called if `set_start_on_harness` is enabled.
193 ///
194 /// # Arguments
195 ///
196 /// * `cpu` - The CPU to initially trace and post timeout events on. This should typically be
197 /// the CPU that is running the code receiving the input this function returns.
198 ///
199 /// # Return Value
200 ///
201 /// Returns an [`AttrValue`] list of integers. Integers are `u8` sized, in the range 0-255.
202 pub fn start_without_buffer(&mut self, cpu: *mut ConfObject) -> Result<AttrValue> {
203 if !self.have_initial_snapshot() {
204 // Start the fuzzer thread early so we can get a testcase
205 self.start_fuzzer_thread()?;
206 }
207
208 let testcase = self.get_testcase()?;
209
210 self.stop_simulation(StopReason::ManualStartWithoutBuffer { processor: cpu })?;
211
212 Ok(testcase.testcase.bytes().to_vec().try_into()?)
213 }
214
215 /// Interface method to manually signal to stop a testcase execution. When this
216 /// method is called, the current testcase execution will be stopped as if it had
217 /// finished executing normally, and the state will be restored according to
218 /// `snapshot_restore_interval` (restoring every iteration by default). This method is
219 /// particularly useful in callbacks triggered on breakpoints or other complex
220 /// conditions. This method does
221 /// not need to be called if `set_stop_on_harness` is enabled.
222 pub fn stop(&mut self) -> Result<()> {
223 debug!(self.as_conf_object(), "stop");
224
225 self.stop_simulation(StopReason::ManualStop)?;
226
227 Ok(())
228 }
229
230 /// Interface method to manually signal to stop execution with a solution condition.
231 /// When this method is called, the current testcase execution will be stopped as if
232 /// it had finished executing with an exception or timeout, and, if an initial
233 /// snapshot exists, it will be restored before the next iteration resumes.
234 pub fn solution(&mut self, id: u64, message: *mut c_char) -> Result<()> {
235 // SAFETY: Simics passes NULL or a NUL-terminated string valid for this call
236 let message = unsafe { c_str_arg(message, "message") }?;
237
238 debug!(self.as_conf_object(), "solution({id:#x}, {message})");
239
240 self.stop_simulation(StopReason::Solution {
241 kind: SolutionKind::Manual,
242 })?;
243
244 Ok(())
245 }
246}