puffin/
execution.rs

1use std::fmt::{Debug, Display};
2use std::sync::mpsc;
3use std::time::Duration;
4
5use nix::errno::Errno;
6use nix::sys::signal::{kill, Signal};
7use nix::sys::wait::WaitStatus::{self, Exited, Signaled};
8use nix::sys::wait::{waitpid, WaitPidFlag};
9use nix::unistd::{fork, ForkResult, Pid};
10
11use crate::error::Error;
12use crate::protocol::{ProtocolBehavior, ProtocolTypes};
13use crate::put_registry::PutRegistry;
14use crate::trace::{ConfigTrace, Spawner, Trace, TraceContext};
15
16pub trait TraceRunner: Sized {
17    type PB: ProtocolBehavior;
18    type R;
19    type E: Display;
20
21    fn execute<T>(self, trace: T, executed_until: &mut usize) -> Result<Self::R, Self::E>
22    where
23        T: AsRef<Trace<<Self::PB as ProtocolBehavior>::ProtocolTypes>>,
24    {
25        Self::execute_config(self, trace, ConfigTrace::default(), executed_until)
26    }
27
28    fn execute_config<T>(
29        self,
30        trace: T,
31        config_trace: ConfigTrace,
32        executed_until: &mut usize,
33    ) -> Result<Self::R, Self::E>
34    where
35        Self: Sized,
36        T: AsRef<Trace<<Self::PB as ProtocolBehavior>::ProtocolTypes>>;
37}
38
39#[derive(Debug, Clone)]
40pub struct Runner<PB: ProtocolBehavior> {
41    pub registry: PutRegistry<PB>,
42    spawner: Spawner<PB>,
43}
44
45impl<PB: ProtocolBehavior> Runner<PB> {
46    pub fn new(registry: impl Into<PutRegistry<PB>>, spawner: impl Into<Spawner<PB>>) -> Self {
47        Self {
48            registry: registry.into(),
49            spawner: spawner.into(),
50        }
51    }
52}
53
54impl<PB: ProtocolBehavior> TraceRunner for &Runner<PB> {
55    type E = Error;
56    type PB = PB;
57    type R = TraceContext<Self::PB>;
58
59    fn execute_config<T>(
60        self,
61        trace: T,
62        config_trace: ConfigTrace,
63        executed_until: &mut usize,
64    ) -> Result<Self::R, Self::E>
65    where
66        T: AsRef<Trace<<Self::PB as ProtocolBehavior>::ProtocolTypes>>,
67    {
68        if config_trace.with_reseed {
69            // We reseed all PUTs before executing a trace!
70            self.registry.determinism_reseed_all_factories();
71        }
72
73        let mut ctx = TraceContext::new_config(self.spawner.clone(), config_trace);
74        trace
75            .as_ref()
76            .execute(&mut ctx, &mut 0, config_trace.check_security_violation)
77            .map_err(|e| {
78                *executed_until = ctx.executed_until;
79                e
80            })?;
81        *executed_until = ctx.executed_until;
82        Ok(ctx)
83    }
84}
85
86#[derive(Debug)]
87pub struct ForkedRunner<T: TraceRunner> {
88    runner: T,
89    timeout: Option<Duration>,
90}
91
92impl<T: TraceRunner> ForkedRunner<T> {
93    pub const fn new(runner: T) -> Self {
94        Self {
95            runner,
96            timeout: None,
97        }
98    }
99
100    pub fn with_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
101        self.timeout = timeout.into();
102        self
103    }
104}
105
106impl<T> From<T> for ForkedRunner<T>
107where
108    T: TraceRunner,
109{
110    fn from(runner: T) -> Self {
111        Self::new(runner)
112    }
113}
114
115impl<T: TraceRunner + Clone> TraceRunner for &ForkedRunner<T> {
116    type E = ForkError;
117    type PB = T::PB;
118    type R = ExecutionStatus;
119
120    fn execute_config<Tr>(
121        self,
122        trace: Tr,
123        config_trace: ConfigTrace,
124        executed_until: &mut usize,
125    ) -> Result<Self::R, Self::E>
126    where
127        Tr: AsRef<Trace<<Self::PB as ProtocolBehavior>::ProtocolTypes>>,
128    {
129        let runner = self.runner.clone();
130
131        run_in_subprocess(
132            || {
133                let ret = match runner.execute_config(trace, config_trace, executed_until) {
134                    Ok(_) => 0,
135                    Err(e) => {
136                        log::info!("{}", e);
137                        1
138                    }
139                };
140
141                std::process::exit(ret);
142            },
143            self.timeout,
144        )
145    }
146}
147
148/// Run traces on two different PUT to identify differences between the executions
149#[derive(Debug, Clone)]
150pub struct DifferentialRunner<PB: ProtocolBehavior> {
151    registry: PutRegistry<PB>,
152    first_spawner: Spawner<PB>,
153    second_spawner: Spawner<PB>,
154}
155
156impl<PB: ProtocolBehavior> DifferentialRunner<PB> {
157    pub fn new(
158        registry: impl Into<PutRegistry<PB>>,
159        first_spawner: impl Into<Spawner<PB>>,
160        second_spawner: impl Into<Spawner<PB>>,
161    ) -> Self {
162        Self {
163            registry: registry.into(),
164            first_spawner: first_spawner.into(),
165            second_spawner: second_spawner.into(),
166        }
167    }
168}
169
170impl<PB: ProtocolBehavior> TraceRunner for &DifferentialRunner<PB> {
171    type E = Error;
172    type PB = PB;
173    type R = (TraceContext<Self::PB>, TraceContext<Self::PB>);
174
175    /// Execute `trace` on the two PUTs provided by `self`, return `Ok` if both
176    /// execution exhibit no differences, `Err(diff)` else
177    fn execute_config<T>(
178        self,
179        trace: T,
180        config_trace: ConfigTrace,
181        executed_until: &mut usize,
182    ) -> Result<Self::R, Self::E>
183    where
184        T: AsRef<Trace<<Self::PB as ProtocolBehavior>::ProtocolTypes>>,
185    {
186        if config_trace.with_reseed {
187            // We reseed all PUTs before executing a trace!
188            self.registry.determinism_reseed_all_factories();
189        }
190
191        log::debug!("Executing first PUT");
192        let mut first_ctx = TraceContext::new(self.first_spawner.clone());
193        let first_trace_status = trace.as_ref().execute(
194            &mut first_ctx,
195            &mut 0,
196            config_trace.check_security_violation,
197        );
198
199        log::debug!("Executing second PUT");
200        let mut second_ctx = TraceContext::new(self.second_spawner.clone());
201        let second_trace_status = trace.as_ref().execute(
202            &mut second_ctx,
203            &mut 0,
204            config_trace.check_security_violation,
205        );
206
207        // Check execution status first
208        // Only match Error::Put and ignore Error::Term, Error::Fn, etc.
209        let mut diff = vec![];
210        #[cfg(not(feature = "ddyf-disable-status"))]
211        match (&first_trace_status, &second_trace_status) {
212            (Err(Error::Put(put1_error)), Err(Error::Put(put2_error))) => {
213                // If both PUT fail at the same step we consider that they fail for the same
214                // reason
215                if first_ctx.executed_until != second_ctx.executed_until {
216                    diff.push(
217                        crate::differential::StatusDiff {
218                            first_executed_steps: first_ctx.executed_until,
219                            first_status: put1_error.to_string(),
220                            second_executed_steps: second_ctx.executed_until,
221                            second_status: put2_error.to_string(),
222                            total_step: trace.as_ref().steps.len(),
223                        }
224                        .as_trace_difference(),
225                    )
226                }
227            }
228            (Err(Error::Put(put1_error)), second_put_status) => diff.push(
229                crate::differential::StatusDiff {
230                    first_executed_steps: first_ctx.executed_until,
231                    first_status: put1_error.to_string(),
232                    second_executed_steps: second_ctx.executed_until,
233                    second_status: match second_put_status {
234                        Ok(_) => "Success".into(),
235                        Err(e) => e.to_string(),
236                    },
237                    total_step: trace.as_ref().steps.len(),
238                }
239                .as_trace_difference(),
240            ),
241            (first_put_status, Err(Error::Put(put2_error))) => diff.push(
242                crate::differential::StatusDiff {
243                    first_executed_steps: first_ctx.executed_until,
244                    first_status: match first_put_status {
245                        Ok(_) => "Success".into(),
246                        Err(e) => e.to_string(),
247                    },
248                    second_executed_steps: second_ctx.executed_until,
249                    second_status: put2_error.to_string(),
250                    total_step: trace.as_ref().steps.len(),
251                }
252                .as_trace_difference(),
253            ),
254            _ => (),
255        };
256
257        // Maximum executed step on the two PUTs
258        *executed_until = usize::max(first_ctx.executed_until, second_ctx.executed_until);
259
260        //check if we have security claim violation (if security claims are enabled)
261        diff.extend(match (&first_trace_status, &second_trace_status) {
262            (Err(Error::SecurityClaim(put1_err)), Err(Error::SecurityClaim(put2_err))) => {
263                vec![crate::differential::SecurityClaimDiff::BothError {
264                    first_put: put1_err.to_string(),
265                    second_put: put2_err.to_string(),
266                }
267                .as_trace_difference()]
268            }
269            (Err(Error::SecurityClaim(put1_err)), _) => {
270                vec![crate::differential::SecurityClaimDiff::Different {
271                    put: 1,
272                    claim: put1_err.to_string(),
273                }
274                .as_trace_difference()]
275            }
276            (_, Err(Error::SecurityClaim(put2_err))) => {
277                vec![crate::differential::SecurityClaimDiff::Different {
278                    put: 2,
279                    claim: put2_err.to_string(),
280                }
281                .as_trace_difference()]
282            }
283            _ => vec![],
284        });
285
286        // If we have status diff or security violation we return the diffs without checking for
287        // others diffs
288        if diff.is_empty() {
289            // Compare the trace context
290            diff.extend(first_ctx.compare(&second_ctx, &trace.as_ref().descriptors));
291
292            // Apply filter to remove false positives
293            diff = diff
294            .into_iter()
295            .filter(<<PB as ProtocolBehavior>::ProtocolTypes as ProtocolTypes>::differential_fuzzing_filter_diff)
296            .collect();
297        }
298
299        if !diff.is_empty() {
300            return Err(Error::Difference {
301                differences: diff,
302                put1_status: first_trace_status
303                    .err()
304                    .map_or("Success".into(), |x| x.to_string()),
305                put2_status: second_trace_status
306                    .err()
307                    .map_or("Success".into(), |x| x.to_string()),
308            });
309        }
310
311        Ok((first_ctx, second_ctx))
312    }
313
314    fn execute<T>(self, trace: T, executed_until: &mut usize) -> Result<Self::R, Self::E>
315    where
316        T: AsRef<Trace<<Self::PB as ProtocolBehavior>::ProtocolTypes>>,
317    {
318        self.execute_config(trace, ConfigTrace::default(), executed_until)
319    }
320}
321
322#[derive(Debug, Clone)]
323pub struct ForkError {
324    reason: String,
325}
326
327impl std::fmt::Display for ForkError {
328    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
329        write!(f, "forked trace execution error: {}", self.reason)
330    }
331}
332
333impl From<Errno> for ForkError {
334    fn from(e: Errno) -> Self {
335        Self {
336            reason: e.to_string(),
337        }
338    }
339}
340
341pub fn run_in_subprocess<R>(
342    func: R,
343    timeout: impl Into<Option<Duration>>,
344) -> Result<ExecutionStatus, ForkError>
345where
346    R: FnOnce(),
347{
348    fn do_fork<R>(f: R) -> Result<Pid, ForkError>
349    where
350        R: FnOnce(),
351    {
352        match unsafe { fork() }? {
353            ForkResult::Parent { child, .. } => Ok(child),
354            ForkResult::Child => {
355                f();
356                std::process::exit(0);
357            }
358        }
359    }
360
361    fn collect_child(child_pid: impl Into<Pid>) -> Result<ExecutionStatus, ForkError> {
362        let pid = child_pid.into();
363        waitpid(pid, Some(WaitPidFlag::WNOHANG))
364            .try_into()
365            .or_else(|e| {
366                // NOTE Child process has not terminated yet. We kill it.
367                if let Err(errno @ (Errno::EINVAL | Errno::EPERM)) = kill(pid, Signal::SIGKILL) {
368                    log::error!("kill({pid}, SIGKILL) failed: {errno}");
369                    return Err(e);
370                }
371
372                waitpid(pid, Some(WaitPidFlag::empty())).try_into()
373            })
374    }
375
376    let executor_pid = do_fork(func)?;
377
378    let mut watchdog = WatchDog::new();
379    let mut signals = signal_hook::iterator::SignalsInfo::<
380        signal_hook::iterator::exfiltrator::WithOrigin,
381    >::new([signal_hook::consts::SIGUSR1, signal_hook::consts::SIGCHLD])
382    .map_err(|e| ForkError {
383        reason: format!("failed to register signal handlers: {e}"),
384    })?;
385
386    watchdog.start(timeout.into());
387
388    let mut result = ExecutionStatus::Timeout;
389    for info in &mut signals {
390        let source = info.process.map(|p| p.pid);
391        result = match info.signal {
392            signal_hook::consts::SIGUSR1 if source == Some(std::process::id() as i32) => {
393                collect_child(executor_pid).ok();
394                ExecutionStatus::Timeout
395            }
396            signal_hook::consts::SIGCHLD if source == Some(executor_pid.as_raw()) => {
397                collect_child(executor_pid)?
398            }
399            _ => {
400                continue;
401            }
402        };
403        break;
404    }
405
406    Ok(result)
407}
408
409struct WatchDog {
410    channel: Option<mpsc::Sender<()>>,
411}
412
413impl WatchDog {
414    pub const fn new() -> Self {
415        Self { channel: None }
416    }
417
418    pub fn start(&mut self, timeout: Option<Duration>) {
419        let duration = if let Some(duration) = timeout {
420            duration
421        } else {
422            return;
423        };
424
425        let (send, recv) = mpsc::channel::<()>();
426        self.channel = Some(send);
427
428        std::thread::spawn(move || {
429            std::thread::sleep(duration);
430            loop {
431                kill(nix::unistd::Pid::this(), Signal::SIGUSR1).unwrap();
432                if recv.recv_timeout(Duration::from_millis(200)).is_err() {
433                    break;
434                }
435            }
436        });
437    }
438}
439
440#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
441pub enum ExecutionStatus {
442    Timeout,
443    Crashed,
444    Success,
445    Interrupted,
446    Failure(i32),
447}
448
449impl TryFrom<Result<WaitStatus, Errno>> for ExecutionStatus {
450    type Error = ForkError;
451
452    fn try_from(status: Result<WaitStatus, Errno>) -> Result<Self, Self::Error> {
453        match status {
454            Ok(Signaled(_, Signal::SIGSEGV | Signal::SIGABRT, _)) => Ok(Self::Crashed),
455            Ok(Signaled(_, _, _)) => Ok(Self::Interrupted),
456            Ok(Exited(_, code)) => match code {
457                0 => Ok(Self::Success),
458                _ => Ok(Self::Failure(code)),
459            },
460            Ok(s) => Err(ForkError {
461                reason: format!("failed to retrieve process status: {s:?}"),
462            }),
463            Err(e) => Err(ForkError {
464                reason: format!("failed to retrieve process status: {e:?}"),
465            }),
466        }
467    }
468}