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
use std::fmt;
use std::io;

use ipc_channel::ipc::{IpcError, TryRecvError};
use ipc_channel::{Error as BincodeError, ErrorKind as BincodeErrorKind};
use serde::{Deserialize, Serialize};

/// Represents a panic caugh across processes.
///
/// This contains the marshalled panic information so that it can be used
/// for other purposes.
///
/// This is similar to `std::panic::PanicInfo` but can cross process boundaries.
#[derive(Serialize, Deserialize)]
pub struct PanicInfo {
    msg: String,
    pub(crate) location: Option<Location>,
    #[cfg(feature = "backtrace")]
    pub(crate) backtrace: Option<backtrace::Backtrace>,
}

/// Location of a panic.
///
/// This is similar to `std::panic::Location` but can cross process boundaries.
#[derive(Serialize, Deserialize, Debug)]
pub struct Location {
    file: String,
    line: u32,
    column: u32,
}

impl Location {
    pub(crate) fn from_std(loc: &std::panic::Location) -> Location {
        Location {
            file: loc.file().into(),
            line: loc.line(),
            column: loc.column(),
        }
    }

    /// Returns the name of the source file from which the panic originated.
    pub fn file(&self) -> &str {
        &self.file
    }

    /// Returns the line number from which the panic originated.
    pub fn line(&self) -> u32 {
        self.line
    }

    /// Returns the column from which the panic originated.
    pub fn column(&self) -> u32 {
        self.column
    }
}

impl PanicInfo {
    /// Creates a new panic object.
    pub(crate) fn new(s: &str) -> PanicInfo {
        PanicInfo {
            msg: s.into(),
            location: None,
            #[cfg(feature = "backtrace")]
            backtrace: None,
        }
    }

    /// Returns the message of the panic.
    pub fn message(&self) -> &str {
        self.msg.as_str()
    }

    /// Returns the panic location.
    pub fn location(&self) -> Option<&Location> {
        self.location.as_ref()
    }

    /// Returns a reference to the backtrace.
    ///
    /// Typically this backtrace is already resolved because it's currently
    /// not possible to cross the process boundaries with unresolved backtraces.
    #[cfg(feature = "backtrace")]
    pub fn backtrace(&self) -> Option<&backtrace::Backtrace> {
        self.backtrace.as_ref()
    }
}

impl fmt::Debug for PanicInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("PanicInfo")
            .field("message", &self.message())
            .field("location", &self.location())
            .field("backtrace", &{
                #[cfg(feature = "backtrace")]
                {
                    self.backtrace()
                }
                #[cfg(not(feature = "backtrace"))]
                {
                    None::<()>
                }
            })
            .finish()
    }
}

impl fmt::Display for PanicInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.msg)
    }
}

/// Encapsulates errors of the procspawn crate.
///
/// In particular it gives access to remotely captured panics.
#[derive(Debug)]
pub struct SpawnError {
    kind: SpawnErrorKind,
}

#[derive(Debug)]
enum SpawnErrorKind {
    Bincode(BincodeError),
    Io(io::Error),
    Panic(PanicInfo),
    IpcChannelClosed(io::Error),
    Cancelled,
    TimedOut,
}

impl SpawnError {
    /// If a panic ocurred this returns the captured panic info.
    pub fn panic_info(&self) -> Option<&PanicInfo> {
        if let SpawnErrorKind::Panic(ref info) = self.kind {
            Some(info)
        } else {
            None
        }
    }

    /// True if this error comes from a panic.
    pub fn is_panic(&self) -> bool {
        self.panic_info().is_some()
    }

    /// True if this error indicates a cancellation.
    pub fn is_cancellation(&self) -> bool {
        if let SpawnErrorKind::Cancelled = self.kind {
            true
        } else {
            false
        }
    }

    /// True if this error indicates a timeout.
    pub fn is_timeout(&self) -> bool {
        if let SpawnErrorKind::TimedOut = self.kind {
            true
        } else {
            false
        }
    }

    /// True if this means the remote side closed.
    pub fn is_remote_close(&self) -> bool {
        match self.kind {
            SpawnErrorKind::IpcChannelClosed(..) => true,
            _ => false,
        }
    }

    pub(crate) fn new_remote_close() -> SpawnError {
        SpawnError {
            kind: SpawnErrorKind::IpcChannelClosed(io::Error::new(
                io::ErrorKind::ConnectionReset,
                "remote closed",
            )),
        }
    }

    pub(crate) fn new_cancelled() -> SpawnError {
        SpawnError {
            kind: SpawnErrorKind::Cancelled,
        }
    }

    pub(crate) fn new_timeout() -> SpawnError {
        SpawnError {
            kind: SpawnErrorKind::TimedOut,
        }
    }
}

impl std::error::Error for SpawnError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self.kind {
            SpawnErrorKind::Bincode(ref err) => Some(&*err),
            SpawnErrorKind::Io(ref err) => Some(&*err),
            SpawnErrorKind::Panic(_) => None,
            SpawnErrorKind::Cancelled => None,
            SpawnErrorKind::TimedOut => None,
            SpawnErrorKind::IpcChannelClosed(ref err) => Some(&*err),
        }
    }
}

impl fmt::Display for SpawnError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.kind {
            SpawnErrorKind::Bincode(_) => write!(f, "process spawn error: bincode error"),
            SpawnErrorKind::Io(_) => write!(f, "process spawn error: i/o error"),
            SpawnErrorKind::Panic(ref p) => write!(f, "process spawn error: panic: {}", p),
            SpawnErrorKind::Cancelled => write!(f, "process spawn error: call cancelled"),
            SpawnErrorKind::TimedOut => write!(f, "process spawn error: timed out"),
            SpawnErrorKind::IpcChannelClosed(_) => write!(
                f,
                "process spawn error: remote side closed (might have panicked on serialization)"
            ),
        }
    }
}

impl From<BincodeError> for SpawnError {
    fn from(err: BincodeError) -> SpawnError {
        // unwrap nested IO errors
        if let BincodeErrorKind::Io(io_err) = *err {
            return SpawnError::from(io_err);
        }
        SpawnError {
            kind: SpawnErrorKind::Bincode(err),
        }
    }
}

impl From<TryRecvError> for SpawnError {
    fn from(err: TryRecvError) -> SpawnError {
        match err {
            TryRecvError::Empty => SpawnError::new_remote_close(),
            TryRecvError::IpcError(err) => SpawnError::from(err),
        }
    }
}

impl From<IpcError> for SpawnError {
    fn from(err: IpcError) -> SpawnError {
        // unwrap nested IO errors
        match err {
            IpcError::Io(err) => SpawnError::from(err),
            IpcError::Bincode(err) => SpawnError::from(err),
            IpcError::Disconnected => SpawnError::new_remote_close(),
        }
    }
}

impl From<io::Error> for SpawnError {
    fn from(err: io::Error) -> SpawnError {
        if let io::ErrorKind::ConnectionReset = err.kind() {
            return SpawnError {
                kind: SpawnErrorKind::IpcChannelClosed(err),
            };
        }
        SpawnError {
            kind: SpawnErrorKind::Io(err),
        }
    }
}

impl From<PanicInfo> for SpawnError {
    fn from(panic: PanicInfo) -> SpawnError {
        SpawnError {
            kind: SpawnErrorKind::Panic(panic),
        }
    }
}