| 1 | //! Custom types for tracing errors. |
| 2 | use std::io; |
| 3 | |
| 4 | use crate::ptracer::Pid; |
| 5 | |
| 6 | /// Alias for `Result<T, self::Error>`. |
| 7 | pub type Result<T> = std::result::Result<T, Error>; |
| 8 | |
| 9 | /// A tracing error. |
| 10 | /// |
| 11 | /// Tracees are controlled by the tracer, but still impacted by their environment. In |
| 12 | /// particular, they may die unexpectedly while in ptrace-stop. Some errors can be due to |
| 13 | /// this, and will not necessarily be followed by a `wait()` status reporting the tracee's |
| 14 | /// death. This should be observed as an error with a `source` of |
| 15 | /// `nix::Error::Sys(Errno::ESRCH)`. |
| 16 | /// |
| 17 | /// For this reason, tracing programs may need to handle an `ESRCH` error on any |
| 18 | /// `ptrace()` operation. |
| 19 | #[derive(thiserror::Error, Debug)] |
| 20 | pub enum Error { |
| 21 | #[error("Could not attach to tracee = {pid}")] |
| 22 | Attach { |
| 23 | pid: Pid, |
| 24 | source: nix::Error, |
| 25 | }, |
| 26 | |
| 27 | #[error("Tracee died while in ptrace-stop")] |
| 28 | TraceeDied { pid: Pid, source: nix::Error }, |
| 29 | |
| 30 | #[error("Input/output error")] |
| 31 | IO(#[from] io::Error), |
| 32 | |
| 33 | #[error("OS error")] |
| 34 | OS(#[from] nix::Error), |
| 35 | |
| 36 | #[error("Internal error: {0}. Please open an issue at https://github.com/ranweiler/pete/issues")] |
| 37 | Internal(String), |
| 38 | } |
| 39 | |
| 40 | impl Error { |
| 41 | pub fn tracee_died(&self) -> bool { |
| 42 | if let Error::TraceeDied { .. } = self { |
| 43 | true |
| 44 | } else { |
| 45 | false |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | macro_rules! internal_error { |
| 51 | ($ctx: expr) => {{ |
| 52 | return Err($crate::error::Error::Internal($ctx.into())); |
| 53 | }} |
| 54 | } |
| 55 | |
| 56 | pub(crate) trait ResultExt<T> { |
| 57 | /// Maps an `ESRCH` error result to `Error::TraceeDied`. |
| 58 | /// |
| 59 | /// Should only be called on results of `ptrace()` operations on valid tracees known |
| 60 | /// to be in ptrace-stop. |
| 61 | fn died_if_esrch(self, pid: Pid) -> Result<T>; |
| 62 | } |
| 63 | |
| 64 | impl<T> ResultExt<T> for std::result::Result<T, nix::Error> { |
| 65 | fn died_if_esrch(self, pid: Pid) -> Result<T> { |
| 66 | use nix::errno::Errno; |
| 67 | |
| 68 | self.map_err(|err| { |
| 69 | if err == Errno::ESRCH { |
| 70 | Error::TraceeDied { pid, source: err } |
| 71 | } else { |
| 72 | err.into() |
| 73 | } |
| 74 | }) |
| 75 | } |
| 76 | } |