1use std::borrow::Cow;
2use std::cell::Cell;
3use std::default::Default;
4
5use libafl::corpus::{Corpus, Testcase};
6use libafl::events::EventFirer;
7use libafl::executors::ExitKind;
8use libafl::feedbacks::{Feedback, StateInitializer};
9use libafl::observers::ObserversTuple;
10use libafl::prelude::{HasMaxSize, HasRand};
11use libafl::state::HasCorpus;
12use libafl_bolts::{Error, Named};
13use serde::{Deserialize, Serialize};
14
15use crate::fuzzer::stats_stage::DUPLICATES;
16use crate::protocol::ProtocolTypes;
17use crate::trace::Trace;
18
19thread_local! {
20 pub static FAIL_AT_STEP: Cell<Option<usize>> = const { Cell::new(None) };
21 pub static OBJECTIVE_TRIGGERED: Cell<bool> = const { Cell::new(false) };
22 pub static OBJECTIVE_HASH: Cell<Option<u64>> = const { Cell::new(None)};
23}
24
25#[derive(Serialize, Deserialize, Clone, Debug)]
30pub struct ObjectiveFeedback {
31 seen_objectives: std::collections::HashSet<(String, u64)>,
32}
33
34impl ObjectiveFeedback {
35 pub fn new() -> Self {
36 Self {
37 seen_objectives: std::collections::HashSet::new(),
38 }
39 }
40}
41
42impl Named for ObjectiveFeedback {
43 fn name(&self) -> &Cow<'static, str> {
44 &Cow::Borrowed("ObjectiveFeedback")
45 }
46}
47
48impl<S> StateInitializer<S> for ObjectiveFeedback {
49 fn init_state(&mut self, _state: &mut S) -> Result<(), Error> {
50 Ok(())
51 }
52}
53
54impl<EM, I, OT, S> Feedback<EM, I, OT, S> for ObjectiveFeedback
55where
56 OT: ObserversTuple<I, S>,
57 EM: EventFirer<I, S>,
58 S: HasCorpus<I>,
59{
60 fn is_interesting(
65 &mut self,
66 state: &mut S,
67 _: &mut EM,
68 _: &I,
69 _: &OT,
70 _: &ExitKind,
71 ) -> Result<bool, Error> {
72 if OBJECTIVE_TRIGGERED.get() {
73 match OBJECTIVE_HASH.get() {
74 Some(hash) => {
75 let current_idx = state.corpus().current();
76
77 if current_idx.is_none() {
78 return Ok(true); }
81
82 let parent_name: String = match state
83 .corpus()
84 .get(current_idx.unwrap())?
85 .borrow()
86 .filename()
87 .clone()
88 {
89 Some(name) => name,
90 None => return Ok(true),
92 };
93
94 if self.seen_objectives.insert((parent_name, hash)) {
96 return Ok(true);
97 } else {
98 DUPLICATES.increment();
99 return Ok(false); }
101 }
102 None => return Ok(true), }
104 }
105 Ok(false)
106 }
107
108 fn is_interesting_introspection(
109 &mut self,
110 s: &mut S,
111 em: &mut EM,
112 i: &I,
113 ot: &OT,
114 ek: &ExitKind,
115 ) -> Result<bool, Error> {
116 self.is_interesting(s, em, i, ot, ek)
117 }
118}
119
120#[derive(Serialize, Deserialize, Clone, Debug)]
122pub struct MinimizingFeedback<SC, PT>
123where
124 SC: HasRand + HasMaxSize,
125 PT: ProtocolTypes + 'static,
126{
127 enabled: bool,
128 pub(crate) phantom: std::marker::PhantomData<(SC, PT)>,
129}
130
131impl<SC, PT> MinimizingFeedback<SC, PT>
132where
133 SC: HasRand + HasMaxSize,
134 PT: ProtocolTypes + 'static,
135{
136 pub fn new(with_truncation: bool) -> Self {
137 Self {
138 enabled: with_truncation,
139 phantom: Default::default(),
140 }
141 }
142}
143impl<SC, PT> Named for MinimizingFeedback<SC, PT>
144where
145 SC: HasRand + HasMaxSize,
146 PT: ProtocolTypes + 'static,
147{
148 fn name(&self) -> &Cow<'static, str> {
149 &Cow::Borrowed("MinimizingFeedback")
150 }
151}
152
153impl<SC, PT> StateInitializer<SC> for MinimizingFeedback<SC, PT>
154where
155 SC: HasRand + HasMaxSize,
156 PT: ProtocolTypes + 'static,
157{
158 fn init_state(&mut self, _state: &mut SC) -> Result<(), Error> {
159 Ok(())
160 }
161}
162
163impl<EM, OT, SC, PT> Feedback<EM, Trace<PT>, OT, SC> for MinimizingFeedback<SC, PT>
164where
165 SC: HasRand + HasMaxSize,
166 PT: ProtocolTypes + 'static,
167 EM: EventFirer<Trace<PT>, SC>,
168 OT: ObserversTuple<Trace<PT>, SC>,
169{
170 fn is_interesting(
171 &mut self,
172 _: &mut SC,
173 _: &mut EM,
174 _: &Trace<PT>,
175 _: &OT,
176 _: &ExitKind,
177 ) -> Result<bool, Error> {
178 Ok(false)
179 }
180
181 fn is_interesting_introspection(
182 &mut self,
183 _: &mut SC,
184 _: &mut EM,
185 _: &Trace<PT>,
186 _: &OT,
187 _: &ExitKind,
188 ) -> Result<bool, Error> {
189 Ok(false)
190 }
191
192 fn append_metadata(
194 &mut self,
195 _state: &mut SC,
196 _manager: &mut EM,
197 _observers: &OT,
198 testcase: &mut Testcase<Trace<PT>>,
199 ) -> Result<(), Error> {
200 if self.enabled {
201 let possibly_failed_at_step = FAIL_AT_STEP.get();
202 let input_trace = testcase
203 .input_mut()
204 .as_mut()
205 .expect("[MinimizingFeedback::append_metadata] Expected input to be a Trace<PT>");
206 if let Some(failed_at_step) = possibly_failed_at_step {
207 if input_trace.steps.len() >= 2 && failed_at_step <= input_trace.steps.len() - 2 {
208 log::trace!("[b:trace len={}/size={}/{failed_at_step}] [MinimizingFeedback::append_metadata] Truncate.", input_trace.steps.len(), input_trace.size());
211 input_trace.truncate_at_step(failed_at_step + 1); } else {
215 log::trace!("[b:trace len={}/size={}/{failed_at_step}] [MinimizingFeedback::append_metadata] No trunc.",input_trace.steps.len(), input_trace.size());
216 }
217 } else {
218 panic!(
219 "[MinimizingFeedback::append_metadata] no failed step found, not truncating trace"
220 );
221 }
222 }
223 Ok(())
224 }
225}