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
use crate::cargo::TestBinary;
#[cfg(target_os = "linux")]
use crate::ptrace_control::*;
#[cfg(target_os = "linux")]
use crate::statemachine::ProcessInfo;
use crate::statemachine::TracerAction;
use crate::traces::{Location, TraceMap};
use chrono::{offset::Local, SecondsFormat};
#[cfg(target_os = "linux")]
use nix::libc::*;
#[cfg(target_os = "linux")]
use nix::sys::{signal::Signal, wait::WaitStatus};
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashSet;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::Instant;
use tracing::{info, warn};

#[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Event {
    ConfigLaunch(String),
    BinaryLaunch(TestBinary),
    Trace(TraceEvent),
    Marker(Option<()>),
}

#[derive(Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct EventWrapper {
    #[serde(flatten)]
    event: Event,
    // The time this was created in seconds
    created: f64,
}

impl EventWrapper {
    fn new(event: Event, since: Instant) -> Self {
        let created = Instant::now().duration_since(since).as_secs_f64();
        Self { event, created }
    }
}

#[derive(Clone, Default, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct TraceEvent {
    pid: Option<i64>,
    child: Option<i64>,
    signal: Option<String>,
    addr: Option<u64>,
    return_val: Option<i64>,
    location: Option<Location>,
    description: String,
}

impl TraceEvent {
    #[cfg(target_os = "linux")]
    pub(crate) fn new_from_action(action: &TracerAction<ProcessInfo>) -> Self {
        match action {
            TracerAction::TryContinue(t) => TraceEvent {
                pid: Some(t.pid.as_raw().into()),
                signal: t.signal.map(|x| x.to_string()),
                description: "Try continue child".to_string(),
                ..Default::default()
            },
            TracerAction::Continue(t) => TraceEvent {
                pid: Some(t.pid.as_raw().into()),
                signal: t.signal.map(|x| x.to_string()),
                description: "Continue child".to_string(),
                ..Default::default()
            },
            TracerAction::Step(t) => TraceEvent {
                pid: Some(t.pid.as_raw().into()),
                description: "Step child".to_string(),
                ..Default::default()
            },
            TracerAction::Detach(t) => TraceEvent {
                pid: Some(t.pid.as_raw().into()),
                description: "Detach child".to_string(),
                ..Default::default()
            },
            TracerAction::Nothing => TraceEvent {
                description: "Do nothing".to_string(),
                ..Default::default()
            },
        }
    }

    #[cfg(target_os = "linux")]
    pub(crate) fn new_from_wait(wait: &WaitStatus, offset: u64, traces: &TraceMap) -> Self {
        let pid = wait.pid().map(|p| p.as_raw().into());
        let mut event = TraceEvent {
            pid,
            ..Default::default()
        };
        match wait {
            WaitStatus::Exited(_, i) => {
                event.description = "Exited".to_string();
                event.return_val = Some((*i).into());
            }
            WaitStatus::Signaled(_, sig, _) => {
                event.signal = Some(sig.to_string());
                event.description = "Signaled".to_string();
            }
            WaitStatus::Stopped(c, sig) => {
                event.signal = Some(sig.to_string());
                if *sig == Signal::SIGTRAP {
                    event.description = "Stopped".to_string();
                    event.addr = current_instruction_pointer(*c).ok().map(|x| (x - 1) as u64);
                    if let Some(addr) = event.addr {
                        event.location = traces.get_location(addr - offset);
                    }
                } else {
                    event.description = "Non-trace stop".to_string();
                }
            }
            WaitStatus::PtraceEvent(pid, sig, val) => {
                event.signal = Some(sig.to_string());
                match *val {
                    PTRACE_EVENT_CLONE => {
                        event.description = "Ptrace Clone".to_string();
                        if *sig == Signal::SIGTRAP {
                            event.child = get_event_data(*pid).ok();
                        }
                    }
                    PTRACE_EVENT_FORK => {
                        event.description = "Ptrace fork".to_string();
                        if *sig == Signal::SIGTRAP {
                            event.child = get_event_data(*pid).ok();
                        }
                    }
                    PTRACE_EVENT_VFORK => {
                        event.description = "Ptrace vfork".to_string();
                        if *sig == Signal::SIGTRAP {
                            event.child = get_event_data(*pid).ok();
                        }
                    }
                    PTRACE_EVENT_EXEC => {
                        event.description = "Ptrace exec".to_string();
                    }
                    PTRACE_EVENT_EXIT => {
                        event.description = "Ptrace exit".to_string();
                    }
                    _ => {
                        event.description = "Ptrace unknown event".to_string();
                    }
                }
            }
            WaitStatus::Continued(_) => {
                event.description = "Continued".to_string();
            }
            WaitStatus::StillAlive => {
                event.description = "StillAlive".to_string();
            }
            WaitStatus::PtraceSyscall(_) => {
                event.description = "PtraceSyscall".to_string();
            }
        }
        event
    }
}

#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct EventLog {
    events: RefCell<Vec<EventWrapper>>,
    #[serde(skip)]
    start: Option<Instant>,
    manifest_paths: HashSet<PathBuf>,
}

impl EventLog {
    pub fn new(manifest_paths: HashSet<PathBuf>) -> Self {
        Self {
            events: RefCell::new(vec![]),
            start: Some(Instant::now()),
            manifest_paths,
        }
    }

    pub fn push_binary(&self, binary: TestBinary) {
        self.events.borrow_mut().push(EventWrapper::new(
            Event::BinaryLaunch(binary),
            self.start.unwrap(),
        ));
    }

    pub fn push_trace(&self, event: TraceEvent) {
        self.events
            .borrow_mut()
            .push(EventWrapper::new(Event::Trace(event), self.start.unwrap()));
    }

    pub fn push_config(&self, name: String) {
        self.events.borrow_mut().push(EventWrapper::new(
            Event::ConfigLaunch(name),
            self.start.unwrap(),
        ));
    }

    pub fn push_marker(&self) {
        // Prevent back to back markers when we spend a lot of time waiting on events
        if self
            .events
            .borrow()
            .last()
            .filter(|x| matches!(x.event, Event::Marker(_)))
            .is_none()
        {
            self.events
                .borrow_mut()
                .push(EventWrapper::new(Event::Marker(None), self.start.unwrap()));
        }
    }
}

impl Drop for EventLog {
    fn drop(&mut self) {
        let fname = format!(
            "tarpaulin_{}.json",
            Local::now().to_rfc3339_opts(SecondsFormat::Secs, false)
        );
        let path = Path::new(&fname);
        info!("Serializing tarpaulin debug log to {}", path.display());
        if let Ok(output) = File::create(path) {
            if let Err(e) = serde_json::to_writer(output, self) {
                warn!("Failed to serialise or write result: {}", e);
            }
        } else {
            warn!("Failed to create log file");
        }
    }
}