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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! The [`InProcessExecutor`] is a libfuzzer-like executor, that will simply call a function.
//! It should usually be paired with extra error-handling, such as a restarting event manager, to be effective.

use core::{
    ffi::c_void,
    marker::PhantomData,
    ptr::{self, write_volatile},
    sync::atomic::{compiler_fence, Ordering},
};

#[cfg(unix)]
use crate::bolts::os::unix_signals::setup_signal_handler;
#[cfg(windows)]
use crate::bolts::os::windows_exceptions::setup_exception_handler;

use crate::{
    corpus::Corpus,
    events::EventManager,
    executors::{
        Executor, ExitKind, HasExecHooks, HasExecHooksTuple, HasObservers, HasObserversHooks,
    },
    feedbacks::Feedback,
    inputs::{HasTargetBytes, Input},
    observers::ObserversTuple,
    state::{HasObjective, HasSolutions},
    Error,
};

/// The inmem executor simply calls a target function, then returns afterwards.
pub struct InProcessExecutor<'a, EM, H, I, OT, S>
where
    H: FnMut(&[u8]) -> ExitKind,
    I: Input + HasTargetBytes,
    OT: ObserversTuple,
{
    /// The harness function, being executed for each fuzzing loop execution
    harness_fn: &'a mut H,
    /// The observers, observing each run
    observers: OT,
    phantom: PhantomData<(EM, I, S)>,
}

impl<'a, EM, H, I, OT, S> Executor<I> for InProcessExecutor<'a, EM, H, I, OT, S>
where
    H: FnMut(&[u8]) -> ExitKind,
    I: Input + HasTargetBytes,
    OT: ObserversTuple,
{
    #[inline]
    fn run_target(&mut self, input: &I) -> Result<ExitKind, Error> {
        let bytes = input.target_bytes();
        let ret = (self.harness_fn)(bytes.as_slice());
        Ok(ret)
    }
}

impl<'a, EM, H, I, OT, S> HasExecHooks<EM, I, S> for InProcessExecutor<'a, EM, H, I, OT, S>
where
    H: FnMut(&[u8]) -> ExitKind,
    I: Input + HasTargetBytes,
    OT: ObserversTuple,
{
    #[inline]
    fn pre_exec(&mut self, _state: &mut S, _event_mgr: &mut EM, _input: &I) -> Result<(), Error> {
        #[cfg(unix)]
        unsafe {
            let data = &mut unix_signal_handler::GLOBAL_STATE;
            write_volatile(
                &mut data.current_input_ptr,
                _input as *const _ as *const c_void,
            );
            write_volatile(
                &mut data.observers_ptr,
                &self.observers as *const _ as *const c_void,
            );
            // 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(&mut data.state_ptr, _state as *mut _ as *mut c_void);
            write_volatile(&mut data.event_mgr_ptr, _event_mgr as *mut _ as *mut c_void);
            compiler_fence(Ordering::SeqCst);
        }
        #[cfg(windows)]
        unsafe {
            let data = &mut windows_exception_handler::GLOBAL_STATE;
            write_volatile(
                &mut data.current_input_ptr,
                _input as *const _ as *const c_void,
            );
            write_volatile(
                &mut data.observers_ptr,
                &self.observers as *const _ as *const c_void,
            );
            // 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(&mut data.state_ptr, _state as *mut _ as *mut c_void);
            write_volatile(&mut data.event_mgr_ptr, _event_mgr as *mut _ as *mut c_void);
            compiler_fence(Ordering::SeqCst);
        }
        Ok(())
    }

    #[inline]
    fn post_exec(&mut self, _state: &mut S, _event_mgr: &mut EM, _input: &I) -> Result<(), Error> {
        #[cfg(unix)]
        unsafe {
            write_volatile(
                &mut unix_signal_handler::GLOBAL_STATE.current_input_ptr,
                ptr::null(),
            );
            compiler_fence(Ordering::SeqCst);
        }
        #[cfg(windows)]
        unsafe {
            write_volatile(
                &mut windows_exception_handler::GLOBAL_STATE.current_input_ptr,
                ptr::null(),
            );
            compiler_fence(Ordering::SeqCst);
        }
        Ok(())
    }
}

impl<'a, EM, H, I, OT, S> HasObservers<OT> for InProcessExecutor<'a, EM, H, I, OT, S>
where
    H: FnMut(&[u8]) -> ExitKind,
    I: Input + HasTargetBytes,
    OT: ObserversTuple,
{
    #[inline]
    fn observers(&self) -> &OT {
        &self.observers
    }

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

impl<'a, EM, H, I, OT, S> HasObserversHooks<EM, I, OT, S> for InProcessExecutor<'a, EM, H, I, OT, S>
where
    H: FnMut(&[u8]) -> ExitKind,
    I: Input + HasTargetBytes,
    OT: ObserversTuple + HasExecHooksTuple<EM, I, S>,
{
}

impl<'a, EM, H, I, OT, S> InProcessExecutor<'a, EM, H, I, OT, S>
where
    H: FnMut(&[u8]) -> ExitKind,
    I: Input + HasTargetBytes,
    OT: ObserversTuple,
{
    /// 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.
    /// * `harness_fn` - the harness, executiong the function
    /// * `observers` - the observers observing the target during execution
    /// This may return an error on unix, if signal handler setup fails
    pub fn new<OC, OF>(
        harness_fn: &'a mut H,
        observers: OT,
        _state: &mut S,
        _event_mgr: &mut EM,
    ) -> Result<Self, Error>
    where
        EM: EventManager<I, S>,
        OC: Corpus<I>,
        OF: Feedback<I>,
        S: HasObjective<OF, I> + HasSolutions<OC, I>,
    {
        #[cfg(unix)]
        unsafe {
            let data = &mut unix_signal_handler::GLOBAL_STATE;
            write_volatile(
                &mut data.crash_handler,
                unix_signal_handler::inproc_crash_handler::<EM, I, OC, OF, OT, S>,
            );
            write_volatile(
                &mut data.timeout_handler,
                unix_signal_handler::inproc_timeout_handler::<EM, I, OC, OF, OT, S>,
            );

            setup_signal_handler(data)?;
            compiler_fence(Ordering::SeqCst);
        }
        #[cfg(windows)]
        unsafe {
            let data = &mut windows_exception_handler::GLOBAL_STATE;
            write_volatile(
                &mut data.crash_handler,
                windows_exception_handler::inproc_crash_handler::<EM, I, OC, OF, OT, S>,
            );
            //write_volatile(
            //    &mut data.timeout_handler,
            //    windows_exception_handler::inproc_timeout_handler::<EM, I, OC, OF, OT, S>,
            //);

            setup_exception_handler(data)?;
            compiler_fence(Ordering::SeqCst);
        }

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

    /// Retrieve the harness function.
    #[inline]
    pub fn harness(&self) -> &H {
        self.harness_fn
    }

    /// Retrieve the harness function for a mutable reference.
    #[inline]
    pub fn harness_mut(&mut self) -> &mut H {
        self.harness_fn
    }
}

#[cfg(unix)]
mod unix_signal_handler {
    use alloc::vec::Vec;
    use core::ptr;
    use libc::{c_void, siginfo_t, ucontext_t};
    #[cfg(feature = "std")]
    use std::io::{stdout, Write};

    use crate::{
        bolts::os::unix_signals::{Handler, Signal},
        corpus::{Corpus, Testcase},
        events::{Event, EventManager},
        executors::ExitKind,
        feedbacks::Feedback,
        inputs::{HasTargetBytes, Input},
        observers::ObserversTuple,
        state::{HasObjective, HasSolutions},
    };

    // TODO merge GLOBAL_STATE with the Windows one

    /// Signal handling on unix systems needs some nasty unsafe.
    pub static mut GLOBAL_STATE: InProcessExecutorHandlerData = InProcessExecutorHandlerData {
        /// The state ptr for signal handling
        state_ptr: ptr::null_mut(),
        /// The event manager ptr for signal handling
        event_mgr_ptr: ptr::null_mut(),
        /// The observers ptr for signal handling
        observers_ptr: ptr::null(),
        /// The current input for signal handling
        current_input_ptr: ptr::null(),
        /// The crash handler fn
        crash_handler: nop_handler,
        /// The timeout handler fn
        timeout_handler: nop_handler,
    };

    pub struct InProcessExecutorHandlerData {
        pub state_ptr: *mut c_void,
        pub event_mgr_ptr: *mut c_void,
        pub observers_ptr: *const c_void,
        pub current_input_ptr: *const c_void,
        pub crash_handler: unsafe fn(Signal, siginfo_t, &mut ucontext_t, data: &mut Self),
        pub timeout_handler: unsafe fn(Signal, siginfo_t, &mut ucontext_t, data: &mut Self),
    }

    unsafe impl Send for InProcessExecutorHandlerData {}
    unsafe impl Sync for InProcessExecutorHandlerData {}

    unsafe fn nop_handler(
        _signal: Signal,
        _info: siginfo_t,
        _context: &mut ucontext_t,
        _data: &mut InProcessExecutorHandlerData,
    ) {
    }

    #[cfg(unix)]
    impl Handler for InProcessExecutorHandlerData {
        fn handle(&mut self, signal: Signal, info: siginfo_t, context: &mut ucontext_t) {
            unsafe {
                let data = &mut GLOBAL_STATE;
                match signal {
                    Signal::SigUser2 | Signal::SigAlarm => {
                        (data.timeout_handler)(signal, info, context, data)
                    }
                    _ => (data.crash_handler)(signal, info, context, data),
                }
            }
        }

        fn signals(&self) -> Vec<Signal> {
            vec![
                Signal::SigAlarm,
                Signal::SigUser2,
                Signal::SigAbort,
                Signal::SigBus,
                Signal::SigPipe,
                Signal::SigFloatingPointException,
                Signal::SigIllegalInstruction,
                Signal::SigSegmentationFault,
                Signal::SigTrap,
            ]
        }
    }

    #[cfg(unix)]
    pub unsafe fn inproc_timeout_handler<EM, I, OC, OF, OT, S>(
        _signal: Signal,
        _info: siginfo_t,
        _context: &mut ucontext_t,
        data: &mut InProcessExecutorHandlerData,
    ) where
        EM: EventManager<I, S>,
        OT: ObserversTuple,
        OC: Corpus<I>,
        OF: Feedback<I>,
        S: HasObjective<OF, I> + HasSolutions<OC, I>,
        I: Input + HasTargetBytes,
    {
        let state = (data.state_ptr as *mut S).as_mut().unwrap();
        let event_mgr = (data.event_mgr_ptr as *mut EM).as_mut().unwrap();
        let observers = (data.observers_ptr as *const OT).as_ref().unwrap();

        if data.current_input_ptr.is_null() {
            #[cfg(feature = "std")]
            dbg!("TIMEOUT or SIGUSR2 happened, but currently not fuzzing. Exiting");
        } else {
            #[cfg(feature = "std")]
            println!("Timeout in fuzz run.");
            #[cfg(feature = "std")]
            let _ = stdout().flush();

            let input = (data.current_input_ptr as *const I).as_ref().unwrap();
            data.current_input_ptr = ptr::null();

            let interesting = state
                .objective_mut()
                .is_interesting(&input, observers, &ExitKind::Timeout)
                .expect("In timeout handler objective failure.");
            if interesting {
                let mut new_testcase = Testcase::new(input.clone());
                state
                    .objective_mut()
                    .append_metadata(&mut new_testcase)
                    .expect("Failed adding metadata");
                state
                    .solutions_mut()
                    .add(new_testcase)
                    .expect("In timeout handler solutions failure.");
                event_mgr
                    .fire(
                        state,
                        Event::Objective {
                            objective_size: state.solutions().count(),
                        },
                    )
                    .expect("Could not send timeouting input");
            }

            event_mgr.on_restart(state).unwrap();

            #[cfg(feature = "std")]
            println!("Waiting for broker...");
            event_mgr.await_restart_safe();
            #[cfg(feature = "std")]
            println!("Bye!");

            event_mgr.await_restart_safe();

            libc::_exit(1);
        }
    }

    /// Crash-Handler for in-process fuzzing.
    /// Will be used for signal handling.
    /// It will store the current State to shmem, then exit.
    #[allow(clippy::too_many_lines)]
    pub unsafe fn inproc_crash_handler<EM, I, OC, OF, OT, S>(
        _signal: Signal,
        _info: siginfo_t,
        _context: &mut ucontext_t,
        data: &mut InProcessExecutorHandlerData,
    ) where
        EM: EventManager<I, S>,
        OT: ObserversTuple,
        OC: Corpus<I>,
        OF: Feedback<I>,
        S: HasObjective<OF, I> + HasSolutions<OC, I>,
        I: Input + HasTargetBytes,
    {
        #[cfg(all(target_os = "android", target_arch = "aarch64"))]
        let _context = *(((_context as *mut _ as *mut c_void as usize) + 128) as *mut c_void
            as *mut ucontext_t);

        #[cfg(feature = "std")]
        println!("Crashed with {}", _signal);
        if data.current_input_ptr.is_null() {
            #[cfg(feature = "std")]
            {
                println!("Double crash\n");
                #[cfg(target_os = "android")]
                let si_addr =
                    { ((_info._pad[0] as usize) | ((_info._pad[1] as usize) << 32)) as usize };
                #[cfg(not(target_os = "android"))]
                let si_addr = { _info.si_addr() as usize };

                println!(
                "We crashed at addr 0x{:x}, but are not in the target... Bug in the fuzzer? Exiting.",
                si_addr
                );
            }
            // let's yolo-cat the maps for debugging, if possible.
            #[cfg(all(target_os = "linux", feature = "std"))]
            match std::fs::read_to_string("/proc/self/maps") {
                Ok(maps) => println!("maps:\n{}", maps),
                Err(e) => println!("Couldn't load mappings: {:?}", e),
            };
            #[cfg(feature = "std")]
            {
                println!("Type QUIT to restart the child");
                let mut line = String::new();
                while line.trim() != "QUIT" {
                    std::io::stdin().read_line(&mut line).unwrap();
                }
            }

            // TODO tell the parent to not restart
            libc::_exit(1);
        } else {
            let state = (data.state_ptr as *mut S).as_mut().unwrap();
            let event_mgr = (data.event_mgr_ptr as *mut EM).as_mut().unwrap();
            let observers = (data.observers_ptr as *const OT).as_ref().unwrap();

            #[cfg(feature = "std")]
            println!("Child crashed!");

            #[cfg(all(
                feature = "std",
                any(target_os = "linux", target_os = "android"),
                target_arch = "aarch64"
            ))]
            {
                use crate::utils::find_mapping_for_address;
                println!("{:━^100}", " CRASH ");
                println!(
                    "Received signal {} at 0x{:016x}, fault address: 0x{:016x}",
                    _signal, _context.uc_mcontext.pc, _context.uc_mcontext.fault_address
                );
                if let Ok((start, _, _, path)) =
                    find_mapping_for_address(_context.uc_mcontext.pc as usize)
                {
                    println!(
                        "pc is at offset 0x{:08x} in  {}",
                        _context.uc_mcontext.pc as usize - start,
                        path
                    );
                }

                println!("{:━^100}", " REGISTERS ");
                for reg in 0..31 {
                    print!(
                        "x{:02}: 0x{:016x} ",
                        reg, _context.uc_mcontext.regs[reg as usize]
                    );
                    if reg % 4 == 3 {
                        println!();
                    }
                }
                println!("pc : 0x{:016x} ", _context.uc_mcontext.pc);

                //println!("{:━^100}", " BACKTRACE ");
                //println!("{:?}", backtrace::Backtrace::new())
            }

            #[cfg(feature = "std")]
            let _ = stdout().flush();

            let input = (data.current_input_ptr as *const I).as_ref().unwrap();
            // Make sure we don't crash in the crash handler forever.
            data.current_input_ptr = ptr::null();

            let interesting = state
                .objective_mut()
                .is_interesting(&input, observers, &ExitKind::Crash)
                .expect("In crash handler objective failure.");
            if interesting {
                let new_input = input.clone();
                let mut new_testcase = Testcase::new(new_input);
                state
                    .objective_mut()
                    .append_metadata(&mut new_testcase)
                    .expect("Failed adding metadata");
                state
                    .solutions_mut()
                    .add(new_testcase)
                    .expect("In crash handler solutions failure.");
                event_mgr
                    .fire(
                        state,
                        Event::Objective {
                            objective_size: state.solutions().count(),
                        },
                    )
                    .expect("Could not send crashing input");
            }

            event_mgr.on_restart(state).unwrap();

            #[cfg(feature = "std")]
            println!("Waiting for broker...");
            event_mgr.await_restart_safe();
            #[cfg(feature = "std")]
            println!("Bye!");

            libc::_exit(1);
        }
    }
}

#[cfg(windows)]
mod windows_exception_handler {
    use alloc::vec::Vec;
    use core::{ffi::c_void, ptr};
    #[cfg(feature = "std")]
    use std::io::{stdout, Write};

    use crate::{
        bolts::{
            bindings::windows::win32::system_services::ExitProcess,
            os::windows_exceptions::{
                ExceptionCode, Handler, CRASH_EXCEPTIONS, EXCEPTION_POINTERS,
            },
        },
        corpus::{Corpus, Testcase},
        events::{Event, EventManager},
        executors::ExitKind,
        feedbacks::Feedback,
        inputs::{HasTargetBytes, Input},
        observers::ObserversTuple,
        state::{HasObjective, HasSolutions},
    };

    /// Signal handling on unix systems needs some nasty unsafe.
    pub static mut GLOBAL_STATE: InProcessExecutorHandlerData = InProcessExecutorHandlerData {
        /// The state ptr for signal handling
        state_ptr: ptr::null_mut(),
        /// The event manager ptr for signal handling
        event_mgr_ptr: ptr::null_mut(),
        /// The observers ptr for signal handling
        observers_ptr: ptr::null(),
        /// The current input for signal handling
        current_input_ptr: ptr::null(),
        /// The crash handler fn
        crash_handler: nop_handler,
        // The timeout handler fn
        //timeout_handler: nop_handler,
    };

    pub struct InProcessExecutorHandlerData {
        pub state_ptr: *mut c_void,
        pub event_mgr_ptr: *mut c_void,
        pub observers_ptr: *const c_void,
        pub current_input_ptr: *const c_void,
        pub crash_handler: unsafe fn(ExceptionCode, *mut EXCEPTION_POINTERS, &mut Self),
        //pub timeout_handler: unsafe fn(ExceptionCode, *mut EXCEPTION_POINTERS, &mut Self),
    }

    unsafe impl Send for InProcessExecutorHandlerData {}
    unsafe impl Sync for InProcessExecutorHandlerData {}

    unsafe fn nop_handler(
        _code: ExceptionCode,
        _exception_pointers: *mut EXCEPTION_POINTERS,
        _data: &mut InProcessExecutorHandlerData,
    ) {
    }

    impl Handler for InProcessExecutorHandlerData {
        fn handle(&mut self, code: ExceptionCode, exception_pointers: *mut EXCEPTION_POINTERS) {
            unsafe {
                let data = &mut GLOBAL_STATE;
                (data.crash_handler)(code, exception_pointers, data)
            }
        }

        fn exceptions(&self) -> Vec<ExceptionCode> {
            CRASH_EXCEPTIONS.to_vec()
        }
    }

    pub unsafe fn inproc_crash_handler<EM, I, OC, OF, OT, S>(
        code: ExceptionCode,
        exception_pointers: *mut EXCEPTION_POINTERS,
        data: &mut InProcessExecutorHandlerData,
    ) where
        EM: EventManager<I, S>,
        OT: ObserversTuple,
        OC: Corpus<I>,
        OF: Feedback<I>,
        S: HasObjective<OF, I> + HasSolutions<OC, I>,
        I: Input + HasTargetBytes,
    {
        #[cfg(feature = "std")]
        println!("Crashed with {}", code);
        if !data.current_input_ptr.is_null() {
            let state = (data.state_ptr as *mut S).as_mut().unwrap();
            let event_mgr = (data.event_mgr_ptr as *mut EM).as_mut().unwrap();
            let observers = (data.observers_ptr as *const OT).as_ref().unwrap();

            #[cfg(feature = "std")]
            println!("Child crashed!");
            #[cfg(feature = "std")]
            let _ = stdout().flush();

            let input = (data.current_input_ptr as *const I).as_ref().unwrap();
            // Make sure we don't crash in the crash handler forever.
            data.current_input_ptr = ptr::null();

            let interesting = state
                .objective_mut()
                .is_interesting(&input, observers, &ExitKind::Crash)
                .expect("In crash handler objective failure.");
            if interesting {
                let new_input = input.clone();
                let mut new_testcase = Testcase::new(new_input);
                state
                    .objective_mut()
                    .append_metadata(&mut new_testcase)
                    .expect("Failed adding metadata");
                state
                    .solutions_mut()
                    .add(new_testcase)
                    .expect("In crash handler solutions failure.");
                event_mgr
                    .fire(
                        state,
                        Event::Objective {
                            objective_size: state.solutions().count(),
                        },
                    )
                    .expect("Could not send crashing input");
            }

            event_mgr.on_restart(state).unwrap();

            #[cfg(feature = "std")]
            println!("Waiting for broker...");
            event_mgr.await_restart_safe();
            #[cfg(feature = "std")]
            println!("Bye!");

            ExitProcess(1);
        } else {
            #[cfg(feature = "std")]
            {
                println!("Double crash\n");
                let crash_addr = exception_pointers
                    .as_mut()
                    .unwrap()
                    .exception_record
                    .as_mut()
                    .unwrap()
                    .exception_address as usize;

                println!(
                "We crashed at addr 0x{:x}, but are not in the target... Bug in the fuzzer? Exiting.",
                    crash_addr
                );
            }
            #[cfg(feature = "std")]
            {
                println!("Type QUIT to restart the child");
                let mut line = String::new();
                while line.trim() != "QUIT" {
                    std::io::stdin().read_line(&mut line).unwrap();
                }
            }

            // TODO tell the parent to not restart
            ExitProcess(1);
        }
    }
}

#[cfg(test)]
mod tests {

    use core::marker::PhantomData;

    use crate::{
        bolts::tuples::tuple_list,
        executors::{Executor, ExitKind, InProcessExecutor},
        inputs::NopInput,
    };

    #[test]
    fn test_inmem_exec() {
        let mut harness = |_buf: &[u8]| ExitKind::Ok;

        let mut in_process_executor = InProcessExecutor::<(), _, NopInput, (), ()> {
            harness_fn: &mut harness,
            observers: tuple_list!(),
            phantom: PhantomData,
        };
        let input = NopInput {};
        assert!(in_process_executor.run_target(&input).is_ok());
    }
}