1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
use core::{
    ffi::c_void,
    fmt::{self, Debug, Formatter},
    marker::PhantomData,
    ptr::{self, addr_of_mut, null, write_volatile},
    sync::atomic::{compiler_fence, Ordering},
    time::Duration,
};

use libafl_bolts::tuples::{tuple_list, Merge};
#[cfg(windows)]
use windows::Win32::System::Threading::SetThreadStackGuarantee;

#[cfg(all(feature = "std", target_os = "linux"))]
use crate::executors::hooks::inprocess::HasTimeout;
#[cfg(all(windows, feature = "std"))]
use crate::executors::hooks::inprocess::HasTimeout;
use crate::{
    events::{EventFirer, EventRestarter},
    executors::{
        hooks::{
            inprocess::{InProcessHooks, GLOBAL_STATE},
            ExecutorHooksTuple,
        },
        inprocess::HasInProcessHooks,
        Executor, HasObservers,
    },
    feedbacks::Feedback,
    fuzzer::HasObjective,
    inputs::UsesInput,
    observers::{ObserversTuple, UsesObservers},
    state::{HasCorpus, HasExecutions, HasSolutions, State, UsesState},
    Error,
};

/// The internal state of `GenericInProcessExecutor`.
pub struct GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S>,
    S: State,
{
    /// The observers, observing each run
    pub(super) observers: OT,
    // Crash and timeout hah
    pub(super) hooks: (InProcessHooks<S>, HT),
    phantom: PhantomData<S>,
}

impl<HT, OT, S> Debug for GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S> + Debug,
    S: State,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("GenericInProcessExecutorState")
            .field("observers", &self.observers)
            .finish_non_exhaustive()
    }
}

impl<HT, OT, S> UsesState for GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S>,
    S: State,
{
    type State = S;
}

impl<HT, OT, S> UsesObservers for GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S>,
    S: State,
{
    type Observers = OT;
}

impl<HT, OT, S> HasObservers for GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S>,
    S: State,
{
    #[inline]
    fn observers(&self) -> &OT {
        &self.observers
    }

    #[inline]
    fn observers_mut(&mut self) -> &mut OT {
        &mut self.observers
    }
}

impl<HT, OT, S> GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S>,
    S: State,
{
    /// This function marks the boundary between the fuzzer and the target
    ///
    /// # Safety
    /// This function sets a bunch of raw pointers in global variables, reused in other parts of
    /// the code.
    #[inline]
    pub unsafe fn enter_target<EM, Z>(
        &mut self,
        fuzzer: &mut Z,
        state: &mut <Self as UsesState>::State,
        mgr: &mut EM,
        input: &<Self as UsesInput>::Input,
        executor_ptr: *const c_void,
    ) {
        unsafe {
            let data = addr_of_mut!(GLOBAL_STATE);
            write_volatile(
                addr_of_mut!((*data).current_input_ptr),
                ptr::from_ref(input) as *const c_void,
            );
            write_volatile(addr_of_mut!((*data).executor_ptr), executor_ptr);
            // Direct raw pointers access /aliasing is pretty undefined behavior.
            // Since the state and event may have moved in memory, refresh them right before the signal may happen
            write_volatile(
                addr_of_mut!((*data).state_ptr),
                ptr::from_mut(state) as *mut c_void,
            );
            write_volatile(
                addr_of_mut!((*data).event_mgr_ptr),
                ptr::from_mut(mgr) as *mut c_void,
            );
            write_volatile(
                addr_of_mut!((*data).fuzzer_ptr),
                ptr::from_mut(fuzzer) as *mut c_void,
            );
            compiler_fence(Ordering::SeqCst);
        }
    }

    /// This function marks the boundary between the fuzzer and the target
    #[inline]
    pub fn leave_target<EM, Z>(
        &mut self,
        _fuzzer: &mut Z,
        _state: &mut <Self as UsesState>::State,
        _mgr: &mut EM,
        _input: &<Self as UsesInput>::Input,
    ) {
        unsafe {
            let data = addr_of_mut!(GLOBAL_STATE);

            write_volatile(addr_of_mut!((*data).current_input_ptr), null());
            compiler_fence(Ordering::SeqCst);
        }
    }
}

impl<HT, OT, S> GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S>,
    S: HasExecutions + HasSolutions + HasCorpus + State,
{
    /// Create a new in mem executor with the default timeout (5 sec)
    pub fn generic<E, EM, OF, Z>(
        user_hooks: HT,
        observers: OT,
        fuzzer: &mut Z,
        state: &mut S,
        event_mgr: &mut EM,
    ) -> Result<Self, Error>
    where
        E: Executor<EM, Z, State = S> + HasObservers + HasInProcessHooks<S>,
        EM: EventFirer<State = S> + EventRestarter,
        OF: Feedback<S>,
        S: State,
        Z: HasObjective<Objective = OF, State = S>,
    {
        Self::with_timeout_generic::<E, EM, OF, Z>(
            user_hooks,
            observers,
            fuzzer,
            state,
            event_mgr,
            Duration::from_millis(5000),
        )
    }

    /// Create a new in mem executor with the default timeout and use batch mode(5 sec)
    #[cfg(all(feature = "std", target_os = "linux"))]
    pub fn batched_timeout_generic<E, EM, OF, Z>(
        user_hooks: HT,
        observers: OT,
        fuzzer: &mut Z,
        state: &mut S,
        event_mgr: &mut EM,
        exec_tmout: Duration,
    ) -> Result<Self, Error>
    where
        E: Executor<EM, Z, State = S> + HasObservers + HasInProcessHooks<S>,
        EM: EventFirer<State = S> + EventRestarter,
        OF: Feedback<S>,
        S: State,
        Z: HasObjective<Objective = OF, State = S>,
    {
        let mut me = Self::with_timeout_generic::<E, EM, OF, Z>(
            user_hooks, observers, fuzzer, state, event_mgr, exec_tmout,
        )?;
        me.hooks_mut().0.timer_mut().batch_mode = true;
        Ok(me)
    }

    /// Create a new in mem executor.
    /// Caution: crash and restart in one of them will lead to odd behavior if multiple are used,
    /// depending on different corpus or state.
    /// * `user_hooks` - the hooks run before and after the harness's execution
    /// * `harness_fn` - the harness, executing the function
    /// * `observers` - the observers observing the target during execution
    /// This may return an error on unix, if signal handler setup fails
    pub fn with_timeout_generic<E, EM, OF, Z>(
        user_hooks: HT,
        observers: OT,
        _fuzzer: &mut Z,
        state: &mut S,
        _event_mgr: &mut EM,
        timeout: Duration,
    ) -> Result<Self, Error>
    where
        E: Executor<EM, Z, State = S> + HasObservers + HasInProcessHooks<S>,
        EM: EventFirer<State = S> + EventRestarter,
        OF: Feedback<S>,
        S: State,
        Z: HasObjective<Objective = OF, State = S>,
    {
        let default = InProcessHooks::new::<E, EM, OF, Z>(timeout)?;
        let mut hooks = tuple_list!(default).merge(user_hooks);
        hooks.init_all::<Self>(state);

        #[cfg(windows)]
        // Some initialization necessary for windows.
        unsafe {
            /*
                See https://github.com/AFLplusplus/LibAFL/pull/403
                This one reserves certain amount of memory for the stack.
                If stack overflow happens during fuzzing on windows, the program is transferred to our exception handler for windows.
                However, if we run out of the stack memory again in this exception handler, we'll crash with STATUS_ACCESS_VIOLATION.
                We need this API call because with the llmp_compression
                feature enabled, the exception handler uses a lot of stack memory (in the compression lib code) on release build.
                As far as I have observed, the compression uses around 0x10000 bytes, but for safety let's just reserve 0x20000 bytes for our exception handlers.
                This number 0x20000 could vary depending on the compilers optimization for future compression library changes.
            */
            let mut stack_reserved = 0x20000;
            SetThreadStackGuarantee(&mut stack_reserved)?;
        }

        #[cfg(all(feature = "std", windows))]
        {
            // set timeout for the handler
            *hooks.0.millis_sec_mut() = timeout.as_millis() as i64;
        }

        Ok(Self {
            observers,
            hooks,
            phantom: PhantomData,
        })
    }

    /// The inprocess handlers
    #[inline]
    pub fn hooks(&self) -> &(InProcessHooks<S>, HT) {
        &self.hooks
    }

    /// The inprocess handlers (mutable)
    #[inline]
    pub fn hooks_mut(&mut self) -> &mut (InProcessHooks<S>, HT) {
        &mut self.hooks
    }
}

impl<HT, OT, S> HasInProcessHooks<S> for GenericInProcessExecutorInner<HT, OT, S>
where
    HT: ExecutorHooksTuple<S>,
    OT: ObserversTuple<S>,
    S: State + HasExecutions + HasSolutions + HasCorpus,
{
    /// the timeout handler
    #[inline]
    fn inprocess_hooks(&self) -> &InProcessHooks<S> {
        &self.hooks.0
    }

    /// the timeout handler
    #[inline]
    fn inprocess_hooks_mut(&mut self) -> &mut InProcessHooks<S> {
        &mut self.hooks.0
    }
}