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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
use crate::breakpoint::*;
use crate::cargo::rust_flags;
use crate::config::Config;
use crate::errors::RunError;
use crate::generate_tracemap;
use crate::ptrace_control::*;
use crate::source_analysis::LineAnalysis;
use crate::statemachine::*;
use crate::TestHandle;
use nix::errno::Errno;
use nix::sys::signal::Signal;
use nix::sys::wait::*;
use nix::unistd::Pid;
use nix::Error as NixErr;
use procfs::process::{MMapPath, Process};
use std::collections::{HashMap, HashSet};
use std::ops::RangeBounds;
use std::path::PathBuf;
use tracing::{debug, info, trace, trace_span, warn};

/// Handle to linux process state
pub struct LinuxData<'a> {
    /// Recent results from waitpid to be handled by statemachine
    wait_queue: Vec<WaitStatus>,
    /// Pending action queue, this is for actions where we need to wait one cycle before we can
    /// apply them :sobs:
    pending_actions: Vec<TracerAction<ProcessInfo>>,
    /// Parent pid of the test
    parent: Pid,
    /// Current Pid to process
    current: Pid,
    /// Program config
    config: &'a Config,
    /// Optional event log to update as the test progresses
    event_log: &'a Option<EventLog>,
    /// Instrumentation points in code with associated coverage data
    traces: &'a mut TraceMap,
    /// Source analysis, needed in case we need to follow any executables
    analysis: &'a HashMap<PathBuf, LineAnalysis>,
    /// Processes we're tracing
    processes: HashMap<Pid, TracedProcess>,
    /// Map from pids to their parent
    pid_map: HashMap<Pid, Pid>,
    /// So if we have the exit code but we're also waiting for all the spawned processes to end
    exit_code: Option<i32>,
}

#[derive(Debug)]
pub struct TracedProcess {
    /// Map of addresses to breakpoints
    breakpoints: HashMap<u64, Breakpoint>,
    /// Thread count. Hopefully getting rid of in future
    thread_count: isize,
    /// Breakpoint offset
    offset: u64,
    /// Instrumentation points in code with associated coverage data
    /// If this is the root tracemap we don't use it...
    traces: Option<TraceMap>,
    /// Parent pid of the process
    parent: Pid,
    /// Whether the process is part of the test binary, or the result of an exec or fork
    is_test_proc: bool,
}

pub fn create_state_machine<'a>(
    test: impl Into<TestHandle>,
    traces: &'a mut TraceMap,
    source_analysis: &'a HashMap<PathBuf, LineAnalysis>,
    config: &'a Config,
    event_log: &'a Option<EventLog>,
) -> (TestState, LinuxData<'a>) {
    let mut data = LinuxData::new(traces, source_analysis, config, event_log);
    let handle = test.into();
    match handle {
        TestHandle::Id(test) => {
            data.parent = test;
        }
        _ => unreachable!("Test handle must be a PID for ptrace engine"),
    }
    (TestState::start_state(), data)
}

pub type UpdateContext = (TestState, TracerAction<ProcessInfo>);

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct ProcessInfo {
    pub(crate) pid: Pid,
    pub(crate) signal: Option<Signal>,
}

impl ProcessInfo {
    fn new(pid: Pid, signal: Option<Signal>) -> Self {
        Self { pid, signal }
    }
}

impl From<Pid> for ProcessInfo {
    fn from(pid: Pid) -> Self {
        ProcessInfo::new(pid, None)
    }
}

impl From<&Pid> for ProcessInfo {
    fn from(pid: &Pid) -> Self {
        ProcessInfo::new(*pid, None)
    }
}

fn get_offset(pid: Pid, config: &Config) -> u64 {
    if rust_flags(config).contains("dynamic-no-pic") {
        0
    } else if let Ok(proc) = Process::new(pid.as_raw()) {
        let exe = proc.exe().ok();
        if let Ok(maps) = proc.maps() {
            let offset_info = maps.iter().find(|x| match (&x.pathname, exe.as_ref()) {
                (MMapPath::Path(p), Some(e)) => p == e,
                (MMapPath::Path(_), None) => true,
                _ => false,
            });
            if let Some(first) = offset_info {
                first.address.0
            } else {
                0
            }
        } else {
            0
        }
    } else {
        0
    }
}

impl<'a> StateData for LinuxData<'a> {
    fn start(&mut self) -> Result<Option<TestState>, RunError> {
        match waitpid(self.current, Some(WaitPidFlag::WNOHANG)) {
            Ok(WaitStatus::StillAlive) => Ok(None),
            Ok(sig @ WaitStatus::Stopped(_, Signal::SIGTRAP)) => {
                if let WaitStatus::Stopped(child, _) = sig {
                    self.current = child;
                }
                trace!("Caught inferior transitioning to Initialise state");
                Ok(Some(TestState::Initialise))
            }
            Ok(_) => Err(RunError::TestRuntime(
                "Unexpected signal when starting test".to_string(),
            )),
            Err(e) => Err(RunError::TestRuntime(format!(
                "Error when starting test: {}",
                e
            ))),
        }
    }

    fn init(&mut self) -> Result<TestState, RunError> {
        let mut traced_process = self.init_process(self.current, None)?;
        traced_process.is_test_proc = true;

        if continue_exec(traced_process.parent, None).is_ok() {
            trace!("Initialised inferior, transitioning to wait state");
            self.processes.insert(self.current, traced_process);
            Ok(TestState::wait_state())
        } else {
            Err(RunError::TestRuntime(
                "Test didn't launch correctly".to_string(),
            ))
        }
    }

    fn last_wait_attempt(&mut self) -> Result<Option<TestState>, RunError> {
        if let Some(ec) = self.exit_code {
            let parent = self.parent;
            for (_, process) in self.processes.iter().filter(|(k, _)| **k != parent) {
                if let Some(tm) = process.traces.as_ref() {
                    self.traces.merge(tm);
                }
            }
            Ok(Some(TestState::End(ec)))
        } else {
            Ok(None)
        }
    }

    fn wait(&mut self) -> Result<Option<TestState>, RunError> {
        let mut result = Ok(None);
        let mut running = true;
        while running {
            let wait = waitpid(
                Pid::from_raw(-1),
                Some(WaitPidFlag::WNOHANG | WaitPidFlag::__WALL),
            );
            match wait {
                Ok(WaitStatus::StillAlive) => {
                    running = false;
                }
                Ok(WaitStatus::Exited(_, _)) => {
                    self.wait_queue.push(wait.unwrap());
                    result = Ok(Some(TestState::Stopped));
                    running = false;
                }
                Ok(WaitStatus::PtraceEvent(_, _, _)) => {
                    self.wait_queue.push(wait.unwrap());
                    result = Ok(Some(TestState::Stopped));
                    running = false;
                }
                Ok(s) => {
                    self.wait_queue.push(s);
                    result = Ok(Some(TestState::Stopped));
                }
                Err(_) if self.exit_code.is_some() => {
                    running = false;
                    result = self.last_wait_attempt();
                }
                Err(e) => {
                    running = false;
                    result = Err(RunError::TestRuntime(format!(
                        "An error occurred while waiting for response from test: {}",
                        e
                    )));
                }
            }
        }
        if !self.wait_queue.is_empty() {
            trace!("Result queue is {:?}", self.wait_queue);
        } else {
            self.apply_pending_actions(..);
        }
        result
    }

    fn stop(&mut self) -> Result<TestState, RunError> {
        let mut actions = Vec::new();
        let mut pcs = HashMap::new();
        let mut result = Ok(TestState::wait_state());
        let pending = self.wait_queue.clone();
        let pending_action_len = self.pending_actions.len();
        self.wait_queue.clear();
        for status in &pending {
            let span = trace_span!("pending", event=?status.pid());
            let _enter = span.enter();
            if let Some(log) = self.event_log.as_ref() {
                let offset = if let Some(process) = self.get_traced_process_mut(self.current) {
                    process.offset
                } else {
                    0
                };
                let traces = match self.get_active_trace_map(self.current) {
                    Some(tm) => tm,
                    None => self.traces,
                };
                let event = TraceEvent::new_from_wait(status, offset, traces);
                log.push_trace(event);
            }
            let state = match status {
                WaitStatus::PtraceEvent(c, s, e) => match self.handle_ptrace_event(*c, *s, *e) {
                    Ok(s) => Ok(s),
                    Err(e) => Err(RunError::TestRuntime(format!(
                        "Error occurred when handling ptrace event: {}",
                        e
                    ))),
                },
                WaitStatus::Stopped(c, Signal::SIGTRAP) => {
                    self.current = *c;
                    match self.collect_coverage_data(&mut pcs) {
                        Ok(s) => Ok(s),
                        Err(e) => Err(RunError::TestRuntime(format!(
                            "Error when collecting coverage: {}",
                            e
                        ))),
                    }
                }
                WaitStatus::Stopped(child, Signal::SIGSTOP) => Ok((
                    TestState::wait_state(),
                    TracerAction::Continue(child.into()),
                )),
                WaitStatus::Stopped(_, Signal::SIGSEGV) => Err(RunError::TestRuntime(
                    "A segfault occurred while executing tests".to_string(),
                )),
                WaitStatus::Stopped(child, Signal::SIGILL) => {
                    let pc = current_instruction_pointer(*child).unwrap_or(1) - 1;
                    trace!("SIGILL raised. Child program counter is: 0x{:x}", pc);
                    Err(RunError::TestRuntime(format!(
                        "Error running test - SIGILL raised in {}",
                        child
                    )))
                }
                WaitStatus::Stopped(c, Signal::SIGCHLD) => {
                    Ok((TestState::wait_state(), TracerAction::Continue(c.into())))
                }
                WaitStatus::Stopped(c, s) => {
                    let sig = if self.config.forward_signals {
                        Some(*s)
                    } else {
                        None
                    };
                    let info = ProcessInfo::new(*c, sig);
                    Ok((TestState::wait_state(), TracerAction::TryContinue(info)))
                }
                WaitStatus::Signaled(c, s, f) => {
                    if let Ok(s) = self.handle_signaled(c, s, *f) {
                        Ok(s)
                    } else {
                        Err(RunError::TestRuntime(
                            "Attempting to handle tarpaulin being signaled".to_string(),
                        ))
                    }
                }
                WaitStatus::Exited(child, ec) => {
                    let mut parent = Pid::from_raw(0);
                    if let Some(proc) = self.get_traced_process_mut(*child) {
                        for ref mut value in proc.breakpoints.values_mut() {
                            value.thread_killed(*child);
                        }
                        parent = proc.parent;
                    }
                    if &parent == child {
                        if let Some(removed) = self.processes.remove(&parent) {
                            if parent != self.parent {
                                let traces = removed.traces.unwrap();
                                self.traces.merge(&traces);
                            }
                        }
                    }
                    trace!("Exited {:?} parent {:?}", child, self.parent);
                    if child == &self.parent {
                        if self.processes.is_empty() || !self.config.follow_exec {
                            Ok((TestState::End(*ec), TracerAction::Nothing))
                        } else {
                            self.exit_code = Some(*ec);
                            info!("Test process exited, but spawned processes still running. Continuing tracing");
                            Ok((TestState::wait_state(), TracerAction::Nothing))
                        }
                    } else {
                        match self.exit_code {
                            Some(ec) if self.processes.is_empty() => return Ok(TestState::End(ec)),
                            _ => {
                                // Process may have already been destroyed. This is just incase
                                Ok((
                                    TestState::wait_state(),
                                    TracerAction::TryContinue(self.parent.into()),
                                ))
                            }
                        }
                    }
                }
                _ => Err(RunError::TestRuntime(
                    "An unexpected signal has been caught by tarpaulin!".to_string(),
                )),
            };
            match state {
                Ok((TestState::Waiting { .. }, action)) => {
                    actions.push(action);
                }
                Ok((state, action)) => {
                    result = Ok(state);
                    actions.push(action);
                }
                Err(e) => result = Err(e),
            }
        }
        let mut continued = false;
        let mut actioned_pids = HashSet::new();

        for a in &actions {
            if let Some(d) = a.get_data() {
                if actioned_pids.contains(&d.pid) {
                    trace!("Skipping action '{:?}', pid already sent command", a);
                    continue;
                } else {
                    trace!("No action for {} yet", d.pid);
                }
            } else {
                trace!("No process info for action");
            }
            trace!("Action: {:?}", a);
            if let Some(log) = self.event_log.as_ref() {
                let event = TraceEvent::new_from_action(a);
                log.push_trace(event);
            }
            match a {
                TracerAction::TryContinue(t) => {
                    continued = true;
                    actioned_pids.insert(t.pid);
                    let _ = continue_exec(t.pid, t.signal);
                }
                TracerAction::Continue(t) => {
                    continued = true;
                    actioned_pids.insert(t.pid);
                    continue_exec(t.pid, t.signal)?;
                }
                TracerAction::Step(t) => {
                    continued = true;
                    actioned_pids.insert(t.pid);
                    single_step(t.pid)?;
                }
                TracerAction::Detach(t) => {
                    continued = true;
                    actioned_pids.insert(t.pid);
                    let _ = detach_child(t.pid);
                }
                TracerAction::Nothing => {}
            }
        }
        // Here we assume that no pending actions will exist for things that have currently
        // signaled as stopped in this iteration. Currently, the pending actions are just fork
        // parents that ptrace will stall until child returns so this will hold true. But if that
        // behaviour changes in future the pending action list may need to be pruned more
        // thoroughly
        self.apply_pending_actions(..pending_action_len);

        if !continued && self.exit_code.is_none() {
            trace!("No action suggested to continue tracee. Attempting a continue");
            let _ = continue_exec(self.parent, None);
        }
        result
    }
}

impl<'a> LinuxData<'a> {
    pub fn new(
        traces: &'a mut TraceMap,
        analysis: &'a HashMap<PathBuf, LineAnalysis>,
        config: &'a Config,
        event_log: &'a Option<EventLog>,
    ) -> LinuxData<'a> {
        LinuxData {
            wait_queue: Vec::new(),
            pending_actions: Vec::new(),
            processes: HashMap::new(),
            current: Pid::from_raw(0),
            parent: Pid::from_raw(0),
            traces,
            analysis,
            config,
            event_log,
            pid_map: HashMap::new(),
            exit_code: None,
        }
    }

    fn get_parent(&self, pid: Pid) -> Option<Pid> {
        self.pid_map.get(&pid).copied().or_else(|| {
            let mut parent_pid = None;
            'outer: for k in self.processes.keys() {
                let proc = Process::new(k.as_raw()).ok()?;
                if let Ok(tasks) = proc.tasks() {
                    for task in tasks.filter_map(Result::ok) {
                        if task.tid == pid.as_raw() {
                            parent_pid = Some(*k);
                            break 'outer;
                        }
                    }
                }
            }
            parent_pid
        })
    }

    fn get_traced_process_mut(&mut self, pid: Pid) -> Option<&mut TracedProcess> {
        let parent = self.get_parent(pid)?;
        self.processes.get_mut(&parent)
    }

    fn get_active_trace_map_mut(&mut self, pid: Pid) -> Option<&mut TraceMap> {
        let parent = self.get_parent(pid)?;
        let process = self.processes.get_mut(&parent)?;
        if process.traces.is_some() {
            process.traces.as_mut()
        } else {
            Some(self.traces)
        }
    }

    fn get_active_trace_map(&mut self, pid: Pid) -> Option<&TraceMap> {
        let parent = self.get_parent(pid)?;
        let process = self.processes.get(&parent)?;
        Some(process.traces.as_ref().unwrap_or(self.traces))
    }

    fn init_process(
        &mut self,
        pid: Pid,
        trace_map: Option<TraceMap>,
    ) -> Result<TracedProcess, RunError> {
        let traces = match trace_map.as_ref() {
            Some(s) => s,
            None => self.traces,
        };
        let mut breakpoints = HashMap::new();
        trace_children(pid)?;
        let offset = get_offset(pid, self.config);
        trace!(
            "Initialising process: {}, address offset: 0x{:x}",
            pid,
            offset
        );
        let mut clashes = HashSet::new();
        for trace in traces.all_traces() {
            for addr in &trace.address {
                if clashes.contains(&align_address(*addr)) {
                    trace!(
                        "Skipping {} as it clashes with previously disabled breakpoints",
                        addr
                    );
                    continue;
                }
                match Breakpoint::new(pid, *addr + offset) {
                    Ok(bp) => {
                        let _ = breakpoints.insert(*addr + offset, bp);
                    }
                    Err(e) if e == Errno::EIO => {
                        return Err(RunError::TestRuntime(
                            "Tarpaulin cannot find code addresses check your linker settings."
                                .to_string(),
                        ));
                    }
                    Err(NixErr::UnknownErrno) => {
                        debug!("Instrumentation address clash, ignoring 0x{:x}", addr);
                        // Now to avoid weird false positives lets get rid of the other breakpoint
                        // at this address.
                        let aligned = align_address(*addr);
                        clashes.insert(aligned);
                        let removed_keys = breakpoints
                            .keys()
                            .filter(|x| align_address(*x - offset) == aligned)
                            .copied()
                            .collect::<Vec<_>>();
                        for key in &removed_keys {
                            let breakpoint = breakpoints.remove(key).unwrap();
                            trace!("Disabling clashing breakpoint");
                            if let Err(e) = breakpoint.disable(pid) {
                                error!("Unable to disable breakpoint: {}", e);
                            }
                        }
                    }
                    Err(_) => {
                        return Err(RunError::TestRuntime(
                            "Failed to instrument test executable".to_string(),
                        ));
                    }
                }
            }
        }
        // a processes pid is it's own parent
        match self.pid_map.insert(pid, pid) {
            Some(old) if old != pid => {
                debug!("{} being promoted to parent. Old parent {}", pid, old)
            }
            _ => {}
        }
        Ok(TracedProcess {
            parent: pid,
            breakpoints,
            thread_count: 0,
            offset,
            is_test_proc: false,
            traces: trace_map,
        })
    }

    fn handle_exec(
        &mut self,
        pid: Pid,
    ) -> Result<(TestState, TracerAction<ProcessInfo>), RunError> {
        trace!("Handling process exec");
        let res = Ok((TestState::wait_state(), TracerAction::Continue(pid.into())));

        if let Ok(proc) = Process::new(pid.into()) {
            let exe = match proc.exe() {
                Ok(e) if !e.starts_with(&self.config.target_dir()) => {
                    return Ok((TestState::wait_state(), TracerAction::Detach(pid.into())));
                }
                Ok(e) => e,
                _ => return Ok((TestState::wait_state(), TracerAction::Detach(pid.into()))),
            };
            match generate_tracemap(&exe, self.analysis, self.config) {
                Ok(tm) if !tm.is_empty() => match self.init_process(pid, Some(tm)) {
                    Ok(tp) => {
                        self.processes.insert(pid, tp);
                        Ok((TestState::wait_state(), TracerAction::Continue(pid.into())))
                    }
                    Err(e) => {
                        error!("Failed to init process (attempting continue): {}", e);
                        res
                    }
                },
                _ => {
                    trace!("Failed to create trace map for executable, continuing");
                    res
                }
            }
        } else {
            trace!("Failed to get process info from PID");
            res
        }
    }

    fn handle_ptrace_event(
        &mut self,
        child: Pid,
        sig: Signal,
        event: i32,
    ) -> Result<(TestState, TracerAction<ProcessInfo>), RunError> {
        use nix::libc::*;

        if sig == Signal::SIGTRAP {
            match event {
                PTRACE_EVENT_CLONE => match get_event_data(child) {
                    Ok(t) => {
                        trace!("New thread spawned {}", t);
                        let mut parent = None;
                        if let Some(proc) = self.get_traced_process_mut(child) {
                            proc.thread_count += 1;
                            parent = Some(proc.parent);
                        } else {
                            warn!("Couldn't find parent for {}", child);
                        }
                        if let Some(p) = parent {
                            self.pid_map.insert(Pid::from_raw(t as _), p);
                        }
                        Ok((
                            TestState::wait_state(),
                            TracerAction::Continue(child.into()),
                        ))
                    }
                    Err(e) => {
                        trace!("Error in clone event {:?}", e);
                        Err(RunError::TestRuntime(
                            "Error occurred upon test executable thread creation".to_string(),
                        ))
                    }
                },
                PTRACE_EVENT_FORK => {
                    if let Ok(fork_child) = get_event_data(child) {
                        trace!("Caught fork event. Child {}", fork_child);
                        let parent = if let Some(process) = self.get_traced_process_mut(child) {
                            // Counting a fork as a new thread ?
                            process.thread_count += 1;
                            Some(process.parent)
                        } else {
                            None
                        };
                        if let Some(parent) = parent {
                            self.pid_map.insert(Pid::from_raw(fork_child as _), parent);
                        }
                    } else {
                        trace!("No event data for child");
                    }
                    Ok((
                        TestState::wait_state(),
                        TracerAction::Continue(child.into()),
                    ))
                }
                PTRACE_EVENT_VFORK => {
                    // So VFORK used to be handled the same place as FORK however, from the man
                    // page for posix_spawn:
                    //
                    // > [The] posix_spawn() function commences by calling clone with CLONE_VM and CLONE_VFORK flags.
                    //
                    // This suggests that Command::new().spawn() will result in a
                    // `PTRACE_EVENT_VFORK` not `PTRACE_EVENT_EXEC`
                    if let Ok(fork_child) = get_event_data(child) {
                        let fork_child = Pid::from_raw(fork_child as _);
                        if self.config.follow_exec {
                            // So I've seen some recursive bin calls with vforks... Maybe just assume
                            // every vfork is an exec :thinking:
                            let (state, action) = self.handle_exec(fork_child)?;
                            if self.config.forward_signals {
                                self.pending_actions
                                    .push(TracerAction::Continue(child.into()));
                            }
                            Ok((state, action))
                        } else {
                            Ok((
                                TestState::wait_state(),
                                TracerAction::Continue(child.into()),
                            ))
                        }
                    } else {
                        Ok((
                            TestState::wait_state(),
                            TracerAction::Continue(child.into()),
                        ))
                    }
                }
                PTRACE_EVENT_EXEC => {
                    if self.config.follow_exec {
                        self.handle_exec(child)
                    } else {
                        Ok((TestState::wait_state(), TracerAction::Detach(child.into())))
                    }
                }
                PTRACE_EVENT_EXIT => {
                    trace!("Child exiting");
                    let mut is_parent = false;
                    if let Some(proc) = self.get_traced_process_mut(child) {
                        proc.thread_count -= 1;
                        is_parent |= proc.parent == child;
                    }
                    if !is_parent {
                        self.pid_map.remove(&child);
                    }
                    Ok((
                        TestState::wait_state(),
                        TracerAction::TryContinue(child.into()),
                    ))
                }
                _ => Err(RunError::TestRuntime(format!(
                    "Unrecognised ptrace event {}",
                    event
                ))),
            }
        } else {
            trace!("Unexpected signal with ptrace event {}", event);
            trace!("Signal: {:?}", sig);
            Err(RunError::TestRuntime("Unexpected signal".to_string()))
        }
    }

    fn collect_coverage_data(
        &mut self,
        visited_pcs: &mut HashMap<Pid, HashSet<u64>>,
    ) -> Result<UpdateContext, RunError> {
        let mut action = None;
        let current = self.current;
        let enable = self.config.count;
        let mut hits_to_increment = HashSet::new();
        if let Some(process) = self.get_traced_process_mut(current) {
            let visited = visited_pcs.entry(process.parent).or_default();
            if let Ok(rip) = current_instruction_pointer(current) {
                let rip = (rip - 1) as u64;
                trace!("Hit address 0x{:x}", rip);
                if process.breakpoints.contains_key(&rip) {
                    let bp = process.breakpoints.get_mut(&rip).unwrap();
                    let updated = if visited.contains(&rip) {
                        let _ = bp.jump_to(current);
                        (true, TracerAction::Continue(current.into()))
                    } else {
                        // Don't reenable if multithreaded as can't yet sort out segfault issue
                        if let Ok(x) = bp.process(current, enable) {
                            x
                        } else {
                            // So failed to process a breakpoint.. Still continue to avoid
                            // stalling
                            (false, TracerAction::Continue(current.into()))
                        }
                    };
                    if updated.0 {
                        hits_to_increment.insert(rip - process.offset);
                    }
                    action = Some(updated.1);
                }
            }
        } else {
            warn!("Failed to find process for pid: {}", current);
        }
        if let Some(traces) = self.get_active_trace_map_mut(current) {
            for addr in &hits_to_increment {
                traces.increment_hit(*addr);
            }
        } else {
            warn!("Failed to find traces for pid: {}", current);
        }
        let action = action.unwrap_or_else(|| TracerAction::Continue(current.into()));
        Ok((TestState::wait_state(), action))
    }

    fn handle_signaled(
        &mut self,
        pid: &Pid,
        sig: &Signal,
        flag: bool,
    ) -> Result<UpdateContext, RunError> {
        let parent = self.get_parent(*pid);
        if let Some(p) = parent {
            if let Some(proc) = self.processes.get(&p) {
                if !proc.is_test_proc {
                    let info = ProcessInfo::new(*pid, Some(*sig));
                    return Ok((TestState::wait_state(), TracerAction::TryContinue(info)));
                }
            }
        }
        match (sig, flag) {
            (Signal::SIGKILL, _) => Ok((TestState::wait_state(), TracerAction::Detach(pid.into()))),
            (Signal::SIGTRAP, true) => {
                Ok((TestState::wait_state(), TracerAction::Continue(pid.into())))
            }
            (Signal::SIGCHLD, _) => {
                Ok((TestState::wait_state(), TracerAction::Continue(pid.into())))
            }
            (Signal::SIGTERM, _) => {
                let info = ProcessInfo {
                    pid: *pid,
                    signal: Some(Signal::SIGTERM),
                };
                Ok((TestState::wait_state(), TracerAction::TryContinue(info)))
            }
            _ => Err(RunError::StateMachine("Unexpected stop".to_string())),
        }
    }

    fn apply_pending_actions(&mut self, range: impl RangeBounds<usize>) {
        for a in self.pending_actions.drain(range) {
            if let Some(log) = self.event_log.as_ref() {
                let event = TraceEvent::new_from_action(&a);
                log.push_trace(event);
            }
            match a {
                TracerAction::Continue(t) | TracerAction::TryContinue(t) => {
                    let _ = continue_exec(t.pid, t.signal);
                }
                e => {
                    error!("Pending actions should only be continues: {:?}", e);
                }
            }
        }
    }
}