Skip to main content

dvm_api/
inspection.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
6#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
7#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
8pub struct InspectionWatches {
9    #[serde(
10        default,
11        deserialize_with = "InspectionWatches::read_watch_points",
12        skip_serializing_if = "Option::is_none"
13    )]
14    #[cfg_attr(feature = "typescript", ts(optional))]
15    watch_points: Option<WatchPoints>,
16}
17
18impl InspectionWatches {
19    pub fn into_requested_points(self) -> Result<Option<WatchPoints>, String> {
20        if let Some(points) = &self.watch_points
21            && points.is_empty()
22        {
23            return Err("watch_points must contain at least one watch point".into());
24        }
25        Ok(self.watch_points)
26    }
27
28    fn read_watch_points<'de, D: Deserializer<'de>>(
29        deserializer: D,
30    ) -> Result<Option<WatchPoints>, D::Error> {
31        WatchPoints::deserialize(deserializer).map(Some)
32    }
33}
34
35impl From<InspectionWatches> for WatchPoints {
36    fn from(watches: InspectionWatches) -> Self {
37        watches.watch_points.unwrap_or_default()
38    }
39}
40
41impl From<WatchPoints> for InspectionWatches {
42    fn from(watch_points: WatchPoints) -> Self {
43        Self {
44            watch_points: Some(watch_points),
45        }
46    }
47}
48
49#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(try_from = "Vec<WatchPoint>")]
51#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
52#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
53pub struct WatchPoints(Vec<WatchPoint>);
54
55impl WatchPoints {
56    pub const MAX_WATCH_POINTS: usize = 32;
57
58    pub fn default_step() -> Self {
59        Self(vec![
60            WatchPoint::FileSyscalls,
61            WatchPoint::Processes,
62            WatchPoint::SocketSyscalls,
63        ])
64    }
65
66    pub fn is_empty(&self) -> bool {
67        self.0.is_empty()
68    }
69
70    pub fn as_slice(&self) -> &[WatchPoint] {
71        &self.0
72    }
73}
74
75impl TryFrom<Vec<WatchPoint>> for WatchPoints {
76    type Error = String;
77
78    fn try_from(watch_points: Vec<WatchPoint>) -> Result<Self, Self::Error> {
79        if watch_points.len() > Self::MAX_WATCH_POINTS {
80            return Err(format!(
81                "at most {} watch points are allowed",
82                Self::MAX_WATCH_POINTS
83            ));
84        }
85        Ok(Self(watch_points))
86    }
87}
88
89impl From<WatchPoints> for Vec<WatchPoint> {
90    fn from(points: WatchPoints) -> Self {
91        points.0
92    }
93}
94
95#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(tag = "kind", rename_all = "snake_case")]
97#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
98#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
99pub enum WatchPoint {
100    Syscall,
101    NamedSyscall { name: SyscallName },
102    PageFault,
103    Processes,
104    FileSyscalls,
105    SocketSyscalls,
106}
107
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(try_from = "String", into = "String")]
110#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
111#[cfg_attr(
112    feature = "typescript",
113    ts(type = "string", export_to = "controller-api.ts")
114)]
115pub struct SyscallName(String);
116
117impl SyscallName {
118    pub fn as_str(&self) -> &str {
119        &self.0
120    }
121}
122
123impl TryFrom<String> for SyscallName {
124    type Error = &'static str;
125
126    fn try_from(name: String) -> Result<Self, Self::Error> {
127        const MAX_NAME_BYTES: usize = 64;
128        if !name.is_empty()
129            && name.len() <= MAX_NAME_BYTES
130            && name
131                .bytes()
132                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
133        {
134            Ok(Self(name))
135        } else {
136            Err("a syscall name must be 1 to 64 letters, digits or underscores")
137        }
138    }
139}
140
141impl From<SyscallName> for String {
142    fn from(name: SyscallName) -> Self {
143        name.0
144    }
145}
146
147#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(tag = "kind", rename_all = "snake_case")]
149#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
150#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
151pub enum SeekTarget {
152    #[default]
153    End,
154    /// About where the recording was at this time: progress is sampled a
155    /// millisecond apart.
156    AtNs { ns: u64 },
157    /// Exactly at a thread's event, as a stop names it.
158    Event { thread: u64, event: u64 },
159}
160
161#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
162#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
163#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
164pub struct SeekSandbox {
165    #[serde(default)]
166    pub target: SeekTarget,
167    #[serde(flatten)]
168    pub watches: InspectionWatches,
169}
170
171#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
172pub struct StepPoint {
173    pub thread: u64,
174    pub event: u64,
175    #[serde(flatten)]
176    pub watches: InspectionWatches,
177}
178
179#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
180#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
181#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
182pub struct DvmStop {
183    pub thread: u64,
184    pub process: u64,
185    pub operations: u64,
186    pub event: u64,
187    pub recording_ns: Option<u64>,
188    pub at: StopEvent,
189    pub stats: HashMap<String, u64>,
190}
191
192impl DvmStop {
193    pub fn seek_target(&self) -> SeekTarget {
194        SeekTarget::Event {
195            thread: self.thread,
196            event: self.event,
197        }
198    }
199}
200
201#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
202#[serde(rename_all = "snake_case")]
203#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
204#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
205pub enum StopEvent {
206    Syscall {
207        number: u64,
208        name: String,
209        args: [String; 6],
210        #[serde(default, skip_serializing_if = "Vec::is_empty")]
211        decoded: Vec<DecodedArgument>,
212    },
213    PageFault {
214        address: String,
215        write: bool,
216        present: bool,
217    },
218    Arrival {
219        rip: String,
220    },
221}
222
223#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
224#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
225#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
226pub struct DecodedArgument {
227    pub arg: u8,
228    #[serde(flatten)]
229    pub value: DecodedValue,
230    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
231    pub truncated: bool,
232}
233
234#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
235#[serde(rename_all = "snake_case")]
236#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
237#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
238pub enum DecodedValue {
239    Path(String),
240    Strings(Vec<String>),
241    Address(String),
242    Bytes(String),
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn watch_points_validate_names_and_limits() {
251        let points = serde_json::from_str::<WatchPoints>(
252            r#"[{"kind":"syscall"},{"kind":"named_syscall","name":"openat"},{"kind":"page_fault"},{"kind":"processes"},{"kind":"file_syscalls"},{"kind":"socket_syscalls"}]"#,
253        )
254        .unwrap();
255        assert_eq!(points.as_slice().len(), 6);
256        assert!(
257            serde_json::from_str::<WatchPoint>(
258                r#"{"kind":"named_syscall","name":"openat\nresume"}"#
259            )
260            .is_err()
261        );
262        assert_eq!(
263            serde_json::from_str::<SeekSandbox>("{}").unwrap().target,
264            SeekTarget::End
265        );
266    }
267
268    #[test]
269    fn a_stop_reads_what_dvm_decoded() {
270        let stop: DvmStop = serde_json::from_str(
271            r#"{"thread":7,"process":5,"operations":120,"event":3456,"recording_ns":null,"at":{"syscall":{"number":59,"name":"execve","args":["0x20057d","0x7fffffffeba8","0x0","0x0","0x0","0x0"],"decoded":[{"arg":0,"path":"/bin/cat"},{"arg":1,"strings":["cat","/etc/hosts"],"truncated":true}]}},"stats":{"syscalls":3456}}"#,
272        )
273        .unwrap();
274        let StopEvent::Syscall { decoded, .. } = &stop.at else {
275            panic!("expected a syscall");
276        };
277        assert_eq!(
278            decoded,
279            &[
280                DecodedArgument {
281                    arg: 0,
282                    value: DecodedValue::Path("/bin/cat".to_owned()),
283                    truncated: false,
284                },
285                DecodedArgument {
286                    arg: 1,
287                    value: DecodedValue::Strings(vec!["cat".to_owned(), "/etc/hosts".to_owned()]),
288                    truncated: true,
289                },
290            ]
291        );
292    }
293
294    #[test]
295    fn requests_distinguish_omitted_watches_from_an_empty_list() {
296        let step: StepPoint = serde_json::from_str(r#"{"thread":1,"event":2}"#).unwrap();
297        assert_eq!(step.watches.into_requested_points().unwrap(), None);
298        let step: StepPoint =
299            serde_json::from_str(r#"{"thread":1,"event":2,"watch_points":[]}"#).unwrap();
300        assert!(step.watches.into_requested_points().is_err());
301        assert!(
302            serde_json::from_str::<StepPoint>(r#"{"thread":1,"event":2,"watch_points":null}"#)
303                .is_err()
304        );
305        let stored: InspectionWatches = serde_json::from_str(r#"{"watch_points":[]}"#).unwrap();
306        assert!(WatchPoints::from(stored).is_empty());
307    }
308
309    #[test]
310    fn seek_target_is_the_end_a_time_or_an_event() {
311        assert_eq!(
312            serde_json::from_str::<SeekSandbox>("{}").unwrap().target,
313            SeekTarget::End
314        );
315        assert_eq!(
316            serde_json::from_str::<SeekTarget>(r#"{"kind":"at_ns","ns":42}"#).unwrap(),
317            SeekTarget::AtNs { ns: 42 }
318        );
319        assert_eq!(
320            serde_json::from_str::<SeekTarget>(r#"{"kind":"event","thread":1,"event":2}"#).unwrap(),
321            SeekTarget::Event {
322                thread: 1,
323                event: 2
324            }
325        );
326        assert!(serde_json::from_str::<SeekTarget>(r#"{"kind":"event","thread":1}"#).is_err());
327    }
328
329    #[test]
330    fn stop_event_round_trips_arrival_stops_and_seeks_back_to_its_event() {
331        let raw = r#"{"thread":2,"process":1,"operations":14,"event":21,"recording_ns":500,"at":{"arrival":{"rip":"0x401234"}},"stats":{"syscalls":9}}"#;
332        let stop: DvmStop = serde_json::from_str(raw).unwrap();
333        assert_eq!(
334            stop.at,
335            StopEvent::Arrival {
336                rip: "0x401234".to_owned(),
337            }
338        );
339        assert_eq!(
340            serde_json::from_str::<DvmStop>(&serde_json::to_string(&stop).unwrap()).unwrap(),
341            stop
342        );
343        assert_eq!(
344            stop.seek_target(),
345            SeekTarget::Event {
346                thread: 2,
347                event: 21
348            }
349        );
350    }
351}