Skip to main content

minidumper_child/
lib.rs

1use std::{
2    ffi::{OsStr, OsString},
3    path::{Path, PathBuf},
4    process,
5    sync::Arc,
6    time::Duration,
7};
8
9pub mod client;
10pub mod server;
11
12#[derive(thiserror::Error, Debug)]
13pub enum Error {
14    #[error("Invalid socket name: {0:?}")]
15    InvalidSocketName(OsString),
16    #[error("Failed to spawn process")]
17    SpawnProcess(#[source] std::io::Error),
18    #[error("Failed to attach crash handler")]
19    AttachCrashHandler(#[source] crash_handler::Error),
20    #[error("Faled to send message")]
21    SendMessage(#[source] minidumper::Error),
22    #[error("Failed to create client with socket name {socket_name:?}")]
23    CreateClient {
24        #[source]
25        source: minidumper::Error,
26        socket_name: OwnedSocketName,
27    },
28    #[error("Failed to create server with socket name {socket_name:?}")]
29    CreateServer {
30        #[source]
31        source: minidumper::Error,
32        socket_name: OwnedSocketName,
33    },
34    #[error("Error while running server")]
35    RunServer(#[source] minidumper::Error),
36}
37
38pub struct ClientHandle {
39    client: Arc<minidumper::Client>,
40    _handler: crash_handler::CrashHandler,
41    _child: process::Child,
42}
43
44impl ClientHandle {
45    pub fn send_message(&self, kind: u32, buf: impl AsRef<[u8]>) -> Result<(), Error> {
46        self.client
47            .send_message(kind, buf)
48            .map_err(Error::SendMessage)
49    }
50}
51
52pub type OnProcess = Box<dyn FnOnce(&mut process::Command) + Send + Sync + 'static>;
53pub type OnMinidump = Box<dyn Fn(Vec<u8>, &Path) + Send + Sync + 'static>;
54pub type OnMessage = Box<dyn Fn(u32, Vec<u8>) + Send + Sync + 'static>;
55
56pub struct MinidumperChild {
57    crashes_dir: PathBuf,
58    server_stale_timeout: Duration,
59    client_connect_timeout: Duration,
60    server_env: String,
61    on_process: Option<OnProcess>,
62    on_minidump: Option<OnMinidump>,
63    on_message: Option<OnMessage>,
64}
65
66impl Default for MinidumperChild {
67    fn default() -> Self {
68        Self {
69            crashes_dir: std::env::temp_dir().join("Crashes"),
70            server_stale_timeout: Duration::from_millis(5000),
71            client_connect_timeout: Duration::from_millis(3000),
72            server_env: "_CRASH_REPORTER_SERVER".to_owned(),
73            on_process: None,
74            on_minidump: None,
75            on_message: None,
76        }
77    }
78}
79
80impl MinidumperChild {
81    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
82    pub fn new() -> Self {
83        Self::default()
84    }
85
86    /// Returns whether the current process is the crash reporting server process.
87    pub fn is_crash_reporter_process(&self) -> bool {
88        std::env::var_os(&self.server_env).is_some()
89    }
90
91    /// Configures a callback which can be used to modify the server process.
92    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
93    pub fn on_process<F>(mut self, on_process: F) -> Self
94    where
95        F: FnOnce(&mut process::Command) + Send + Sync + 'static,
96    {
97        self.on_process = Some(Box::new(on_process));
98        self
99    }
100
101    /// Configures a callback which is invoked with the generated minidump on crash.
102    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
103    pub fn on_minidump<F>(mut self, on_minidump: F) -> Self
104    where
105        F: Fn(Vec<u8>, &Path) + Send + Sync + 'static,
106    {
107        self.on_minidump = Some(Box::new(on_minidump));
108        self
109    }
110
111    /// Configures a callback which is invoked with messages from the app process.
112    ///
113    /// A message may be sent using [`ClientHandle::send_message`].
114    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
115    pub fn on_message<F>(mut self, on_message: F) -> Self
116    where
117        F: Fn(u32, Vec<u8>) + Send + Sync + 'static,
118    {
119        self.on_message = Some(Box::new(on_message));
120        self
121    }
122
123    /// Configures the directory where crash dumps will be stored.
124    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
125    pub fn with_crashes_dir(mut self, crashes_dir: PathBuf) -> Self {
126        self.crashes_dir = crashes_dir;
127        self
128    }
129
130    /// Configures the server stale timeout.
131    ///
132    /// The server expects periodic messages from the client process, if it does not receive
133    /// a message within `timeout`, it considers the connection broken and detach.
134    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
135    pub fn with_server_stale_timeout(mut self, timeout: Duration) -> Self {
136        self.server_stale_timeout = timeout;
137        self
138    }
139
140    /// Configures the client connect timeout.
141    ///
142    /// This is the amount of time the client will wait to establish a connection to the server.
143    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
144    pub fn with_client_connect_timeout(mut self, timeout: Duration) -> Self {
145        self.client_connect_timeout = timeout;
146        self
147    }
148
149    /// Configures the name of an environment variable which is passed to the server process.
150    ///
151    /// This defaults to `_CRASH_REPORTER_SERVER`.
152    #[must_use = "You should call spawn() or the crash reporter won't be enabled"]
153    pub fn with_server_env_var(mut self, name: String) -> Self {
154        self.server_env = name;
155        self
156    }
157
158    #[must_use = "The return value of spawn() should not be dropped until the program exits"]
159    pub fn spawn(self) -> Result<ClientHandle, Error> {
160        if self.on_minidump.is_none() && self.on_message.is_none() {
161            panic!("You should set one of 'on_minidump' or 'on_message'");
162        }
163
164        if let Some(socket_name) = std::env::var_os(&self.server_env) {
165            let socket_name = OwnedSocketName::from_os_str(&socket_name)
166                .ok_or(Error::InvalidSocketName(socket_name))?;
167
168            server::start(
169                socket_name,
170                self.crashes_dir,
171                self.server_stale_timeout,
172                self.on_minidump,
173                self.on_message,
174            )?;
175
176            // We force exit so that the app code after here does not run in the
177            // crash reporter process.
178            std::process::exit(0);
179        } else {
180            // We use a unique socket name because we don't share the crash reporter
181            // processes between different instances of the app.
182            let socket_name = OwnedSocketName::new(&std::env::temp_dir(), uuid::Uuid::new_v4());
183
184            std::env::current_exe()
185                .and_then(|current_exe| {
186                    let mut process = process::Command::new(current_exe);
187                    if let Some(on_process) = self.on_process {
188                        on_process(&mut process);
189                    }
190                    // Always set this last, so an accidental `env_clear()` doesn't remove it.
191                    process.env(self.server_env, socket_name.as_os_string());
192                    process.spawn()
193                })
194                .map_err(Error::SpawnProcess)
195                .and_then(|server_process| {
196                    client::start(
197                        socket_name,
198                        self.client_connect_timeout,
199                        server_process.id(),
200                        self.server_stale_timeout / 2,
201                    )
202                    .map(|(client, handler)| ClientHandle {
203                        client,
204                        _handler: handler,
205                        _child: server_process,
206                    })
207                })
208        }
209    }
210}
211
212/// An owned version of [SocketName](minidumper::SocketName).
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub enum OwnedSocketName {
215    Path(PathBuf),
216    #[cfg(any(target_os = "linux", target_os = "android"))]
217    Abstract(String),
218}
219
220impl OwnedSocketName {
221    const PATH_PREFIX: &str = "path:";
222    #[cfg(any(target_os = "linux", target_os = "android"))]
223    const ABSTRACT_PREFIX: &str = "abstract:";
224
225    fn new(base_dir: &Path, session_id: uuid::Uuid) -> Self {
226        #[cfg(any(target_os = "linux", target_os = "android"))]
227        {
228            return Self::Abstract(format!("temp-socket-{}", session_id.simple()));
229        }
230
231        let mut path = base_dir.to_path_buf();
232        path.push(format!("temp-socket-{}", session_id.simple()));
233        Self::Path(path)
234    }
235
236    fn as_ref(&self) -> minidumper::SocketName<'_> {
237        match self {
238            Self::Path(p) => minidumper::SocketName::Path(p.as_path()),
239            #[cfg(any(target_os = "linux", target_os = "android"))]
240            Self::Abstract(s) => minidumper::SocketName::Abstract(s.as_str()),
241        }
242    }
243
244    fn as_os_string(&self) -> OsString {
245        match self {
246            Self::Path(p) => {
247                let mut out = OsString::from(Self::PATH_PREFIX.to_string());
248                out.push(p);
249                out
250            }
251
252            #[cfg(any(target_os = "linux", target_os = "android"))]
253            Self::Abstract(s) => {
254                let mut out = OsString::from(Self::ABSTRACT_PREFIX.to_string());
255                out.push(s);
256                out
257            }
258        }
259    }
260
261    fn from_os_str(os_str: &OsStr) -> Option<Self> {
262        let strip_prefix = |prefix: &OsStr| -> Option<&OsStr> {
263            let rest = os_str
264                .as_encoded_bytes()
265                .strip_prefix(prefix.as_encoded_bytes())?;
266            // SAFETY: The bytes we are passing in were originally an `OsStr`. We only
267            // stripped off a prefix that was also an `OsStr`.
268            unsafe { Some(OsStr::from_encoded_bytes_unchecked(rest)) }
269        };
270
271        let path_prefix: &OsStr = OsStr::new(Self::PATH_PREFIX);
272
273        if let Some(path) = strip_prefix(path_prefix) {
274            return Some(Self::Path(PathBuf::from(path)));
275        }
276
277        #[cfg(any(target_os = "linux", target_os = "android"))]
278        {
279            let abstract_prefix: &OsStr = OsStr::new(Self::ABSTRACT_PREFIX);
280
281            if let Some(name) = strip_prefix(abstract_prefix) {
282                let name = name.to_str()?.to_owned();
283                return Some(Self::Abstract(name));
284            }
285        }
286
287        None
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use std::ffi::OsStr;
294    use std::path::PathBuf;
295
296    use uuid::Uuid;
297
298    use crate::OwnedSocketName;
299
300    #[test]
301    fn owned_socket_name_roundtrip_new() {
302        let sn = OwnedSocketName::new("/tmp".as_ref(), Uuid::new_v4());
303        let os_str = sn.as_os_string();
304        assert_eq!(OwnedSocketName::from_os_str(&os_str).unwrap(), sn);
305    }
306
307    #[test]
308    fn owned_socket_name_roundtrip_path_utf8() {
309        let sn = OwnedSocketName::Path("/tmp/mysocket".into());
310        let os_str = sn.as_os_string();
311        assert_eq!(OwnedSocketName::from_os_str(&os_str).unwrap(), sn);
312    }
313
314    #[cfg(unix)]
315    #[test]
316    fn owned_socket_name_roundtrip_path_unix() {
317        use std::os::unix::ffi::OsStrExt;
318        // Example of a non-UTF-8 path from stdlib docs:
319        // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
320        // respectively. The value 0x80 is a lone continuation byte, invalid
321        // in a UTF-8 sequence.
322        let source = [0x66, 0x6f, 0x80, 0x6f];
323        let path = OsStr::from_bytes(&source[..]);
324        let sn = OwnedSocketName::Path(PathBuf::from(path));
325        let os_str = sn.as_os_string();
326        assert_eq!(OwnedSocketName::from_os_str(&os_str).unwrap(), sn);
327    }
328
329    #[cfg(any(target_os = "linux", target_os = "android"))]
330    #[test]
331    fn owned_socket_name_roundtrip_abstract() {
332        let sn = OwnedSocketName::Abstract("my-tmp-socket".into());
333        let os_str = sn.as_os_string();
334        assert_eq!(OwnedSocketName::from_os_str(&os_str).unwrap(), sn);
335    }
336}