Debian Codegraph @

third_party/rust/crash-context/src/mac/ipc.rs

raw
1 //! Unfortunately, sending a [`CrashContext`] to another process on Macos
2 //! needs to be done via mach ports, as, for example, `mach_task_self` is a
3 //! special handle that needs to be translated into the "actual" task when used
4 //! by another process, this _might_ be possible completely in userspace, but
5 //! examining the source code for this leads me to believe that there are enough
6 //! footguns, particularly around security, that this might take a while, so for
7 //! now, if you need to use a [`CrashContext`] across processes, you need
8 //! to use the IPC mechanisms here to get meaningful/accurate data
9 //!
10 //! Note that in all cases of an optional timeout, a `None` will return
11 //! immediately regardless of whether the messaged has been enqueued or
12 //! dequeued from the kernel queue, so it is _highly_ recommended to use
13 //! reasonable timeouts for sending and receiving messages between processes.
14
15 use crate::CrashContext;
16 use mach2::{
17 bootstrap, kern_return::KERN_SUCCESS, mach_port, message as msg, port, task,
18 traps::mach_task_self,
19 };
20 pub use mach2::{kern_return::kern_return_t, message::mach_msg_return_t};
21 use std::{ffi::CStr, time::Duration};
22
23 extern "C" {
24 /// From <usr/include/mach/mach_traps.h>, there is no binding for this in mach2
25 pub fn pid_for_task(task: port::mach_port_name_t, pid: *mut i32) -> kern_return_t;
26 }
27
28 /// <https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/osfmk/mach/message.h#L379-L391>
29 #[repr(C, packed(4))]
30 struct MachMsgPortDescriptor {
31 name: u32,
32 __pad1: u32,
33 __pad2: u16,
34 disposition: u8,
35 __type: u8,
36 }
37
38 impl MachMsgPortDescriptor {
39 fn new(name: u32, disposition: u32) -> Self {
40 Self {
41 name,
42 disposition: disposition as u8,
43 __pad1: 0,
44 __pad2: 0,
45 __type: msg::MACH_MSG_PORT_DESCRIPTOR as u8,
46 }
47 }
48 }
49
50 #[repr(C, packed(4))]
51 struct MachMsgBody {
52 pub descriptor_count: u32,
53 }
54
55 #[repr(C, packed(4))]
56 pub struct MachMsgTrailer {
57 pub kind: u32,
58 pub size: u32,
59 }
60
61 /// <https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/osfmk/mach/message.h#L545-L552>
62 #[repr(C, packed(4))]
63 struct MachMsgHeader {
64 pub bits: u32,
65 pub size: u32,
66 pub remote_port: u32,
67 pub local_port: u32,
68 pub voucher_port: u32,
69 pub id: u32,
70 }
71
72 /// The actual crash context message sent and received. This message is a single
73 /// struct since it needs to be contiguous block of memory. I suppose it's like
74 /// this because people are expected to use MIG to generate the interface code,
75 /// but it's ugly as hell regardless.
76 #[repr(C, packed(4))]
77 struct CrashContextMessage {
78 head: MachMsgHeader,
79 /// When providing port descriptors, this must be present to say how many
80 /// of them follow the header and body
81 body: MachMsgBody,
82 // These are the really the critical piece of the payload, during
83 // sending (or receiving?) these are turned into descriptors that
84 // can actually be used by another process
85 /// The task that crashed (ie `mach_task_self`)
86 task: MachMsgPortDescriptor,
87 /// The thread that crashed
88 crash_thread: MachMsgPortDescriptor,
89 /// The handler thread, probably, but not necessarily `mach_thread_self`
90 handler_thread: MachMsgPortDescriptor,
91 // Port opened by the client to receive an ack from the server
92 ack_port: MachMsgPortDescriptor,
93 /// Combination of the FLAG_* constants
94 flags: u32,
95 /// The exception type
96 exception_kind: u32,
97 /// The exception code
98 exception_code: u64,
99 /// The optional exception subcode
100 exception_subcode: u64,
101 /// We don't actually send this, but it's tacked on by the kernel :(
102 trailer: MachMsgTrailer,
103 }
104
105 const FLAG_HAS_EXCEPTION: u32 = 0x1;
106 const FLAG_HAS_SUBCODE: u32 = 0x2;
107
108 /// Message sent from the [`Receiver`] upon receiving and handling a [`CrashContextMessage`]
109 #[repr(C, packed(4))]
110 struct AcknowledgementMessage {
111 head: MachMsgHeader,
112 result: u32,
113 }
114
115 /// An error that can occur while interacting with mach ports
116 #[derive(Copy, Clone, Debug)]
117 pub enum Error {
118 /// A kernel error will generally indicate an error occurred while creating
119 /// or modifying a mach port
120 Kernel(kern_return_t),
121 /// A message error indicates an error occurred while sending or receiving
122 /// a message on a mach port
123 Message(mach_msg_return_t),
124 }
125
126 impl std::error::Error for Error {}
127
128 use std::fmt;
129
130 impl fmt::Display for Error {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 // TODO: use a good string for the error codes
133 write!(f, "{:?}", self)
134 }
135 }
136
137 macro_rules! kern {
138 ($call:expr) => {{
139 let res = $call;
140
141 if res != KERN_SUCCESS {
142 return Err(Error::Kernel(res));
143 }
144 }};
145 }
146
147 macro_rules! msg {
148 ($call:expr) => {{
149 let res = $call;
150
151 if res != msg::MACH_MSG_SUCCESS {
152 return Err(Error::Message(res));
153 }
154 }};
155 }
156
157 /// Sends a [`CrashContext`] from a crashing process to another process running
158 /// a [`Server`] with the same name
159 pub struct Client {
160 port: port::mach_port_t,
161 }
162
163 impl Client {
164 /// Attempts to create a new client that can send messages to a [`Server`]
165 /// that was created with the specified name.
166 ///
167 /// # Errors
168 ///
169 /// The specified port is not available for some reason, if you expect the
170 /// port to be created you can retry this function until it connects.
171 pub fn create(name: &CStr) -> Result<Self, Error> {
172 // SAFETY: syscalls. The user has no invariants to uphold, hence the
173 // unsafe not being on the function as a whole
174 unsafe {
175 let mut task_bootstrap_port = 0;
176 kern!(task::task_get_special_port(
177 mach_task_self(),
178 task::TASK_BOOTSTRAP_PORT,
179 &mut task_bootstrap_port
180 ));
181
182 let mut port = 0;
183 kern!(bootstrap::bootstrap_look_up(
184 task_bootstrap_port,
185 name.as_ptr(),
186 &mut port
187 ));
188
189 Ok(Self { port })
190 }
191 }
192
193 /// Sends the specified [`CrashContext`] to a [`Server`].
194 ///
195 /// If the ack from the [`Server`] times out `Ok(None)` is returned, otherwise
196 /// it is the value specified in the [`Server`] process to [`Acknowledger::send_ack`]
197 ///
198 /// # Errors
199 ///
200 /// The send of the [`CrashContext`] or the receive of the ack fails.
201 pub fn send_crash_context(
202 &self,
203 ctx: &CrashContext,
204 send_timeout: Option<Duration>,
205 receive_timeout: Option<Duration>,
206 ) -> Result<Option<u32>, Error> {
207 // SAFETY: syscalls. Again, the user has no invariants to uphold, so
208 // the function itself is not marked unsafe
209 unsafe {
210 // Create a new port to receive a response from the reciving end of
211 // this port so we that we know when it has actually processed the
212 // CrashContext, which is (presumably) interesting for the caller. If
213 // that is not interesting they can set the receive_timeout to 0 to
214 // just return immediately
215 let mut ack_port = AckReceiver::new()?;
216
217 let (flags, exception_kind, exception_code, exception_subcode) =
218 if let Some(exc) = ctx.exception {
219 (
220 FLAG_HAS_EXCEPTION
221 | if exc.subcode.is_some() {
222 FLAG_HAS_SUBCODE
223 } else {
224 0
225 },
226 exc.kind,
227 exc.code,
228 exc.subcode.unwrap_or_default(),
229 )
230 } else {
231 (0, 0, 0, 0)
232 };
233
234 let mut msg = CrashContextMessage {
235 head: MachMsgHeader {
236 bits: msg::MACH_MSG_TYPE_COPY_SEND | msg::MACH_MSGH_BITS_COMPLEX,
237 // We don't send the trailer, that's added by the kernel
238 size: std::mem::size_of::<CrashContextMessage>() as u32 - 8,
239 remote_port: self.port,
240 local_port: port::MACH_PORT_NULL,
241 voucher_port: port::MACH_PORT_NULL,
242 id: 0,
243 },
244 body: MachMsgBody {
245 descriptor_count: 4,
246 },
247 task: MachMsgPortDescriptor::new(ctx.task, msg::MACH_MSG_TYPE_COPY_SEND),
248 crash_thread: MachMsgPortDescriptor::new(ctx.thread, msg::MACH_MSG_TYPE_COPY_SEND),
249 handler_thread: MachMsgPortDescriptor::new(
250 ctx.handler_thread,
251 msg::MACH_MSG_TYPE_COPY_SEND,
252 ),
253 ack_port: MachMsgPortDescriptor::new(ack_port.port, msg::MACH_MSG_TYPE_COPY_SEND),
254 flags,
255 exception_kind,
256 exception_code,
257 exception_subcode,
258 // We don't actually send this but I didn't feel like making
259 // two types
260 trailer: MachMsgTrailer { kind: 0, size: 8 },
261 };
262
263 // Try to actually send the message to the Server
264 msg!(msg::mach_msg(
265 ((&mut msg.head) as *mut MachMsgHeader).cast(),
266 msg::MACH_SEND_MSG | msg::MACH_SEND_TIMEOUT,
267 msg.head.size,
268 0,
269 port::MACH_PORT_NULL,
270 send_timeout
271 .map(|st| st.as_millis() as u32)
272 .unwrap_or_default(),
273 port::MACH_PORT_NULL
274 ));
275
276 // Wait for a response from the Server
277 match ack_port.recv_ack(receive_timeout) {
278 Ok(result) => Ok(Some(result)),
279 Err(Error::Message(msg::MACH_RCV_TIMED_OUT)) => Ok(None),
280 Err(e) => Err(e),
281 }
282 }
283 }
284 }
285
286 /// Returned from [`Server::try_recv_crash_context`] when a [`Client`] has sent
287 /// a crash context
288 pub struct ReceivedCrashContext {
289 /// The crash context sent by a [`Client`]
290 pub crash_context: CrashContext,
291 /// Allows the sending of an ack back to the [`Client`] to acknowledge that
292 /// your code has received and processed the [`CrashContext`]
293 pub acker: Acknowledger,
294 /// The process id of the process the [`Client`] lives in. This is retrieved
295 /// via `pid_for_task`.
296 pub pid: u32,
297 }
298
299 /// Receives a [`CrashContext`] from another process
300 pub struct Server {
301 port: port::mach_port_t,
302 }
303
304 impl Server {
305 /// Creates a new [`Server`] "bound" to the specified service name.
306 ///
307 /// # Errors
308 ///
309 /// We fail to acquire the bootstrap port, or fail to register the service.
310 pub fn create(name: &CStr) -> Result<Self, Error> {
311 // SAFETY: syscalls. Again, the caller has no invariants to uphold, so
312 // the entire function is not marked as unsafe
313 unsafe {
314 let mut task_bootstrap_port = 0;
315 kern!(task::task_get_special_port(
316 mach_task_self(),
317 task::TASK_BOOTSTRAP_PORT,
318 &mut task_bootstrap_port
319 ));
320
321 let mut port = 0;
322 // Note that Breakpad uses bootstrap_register instead of this function as
323 // MacOS 10.5 apparently deprecated bootstrap_register and then provided
324 // bootstrap_check_in, but broken. However, 10.5 had its most recent update
325 // over 13 years ago, and is not supported by Apple, so why should we?
326 kern!(bootstrap::bootstrap_check_in(
327 task_bootstrap_port,
328 name.as_ptr(),
329 &mut port,
330 ));
331
332 Ok(Self { port })
333 }
334 }
335
336 /// Attempts to retrieve a [`CrashContext`] sent from a crashing process.
337 ///
338 /// Note that in event of a timeout, this method will return `Ok(None)` to
339 /// indicate that a crash context was unavailable rather than an error.
340 ///
341 /// # Errors
342 ///
343 /// We fail to receive the [`CrashContext`] message for a reason other than
344 /// one not being in the queue, or we fail to translate the task identifier
345 /// into a pid
346 pub fn try_recv_crash_context(
347 &mut self,
348 timeout: Option<Duration>,
349 ) -> Result<Option<ReceivedCrashContext>, Error> {
350 // SAFETY: syscalls. The caller has no invariants to uphold, so the
351 // entire function is not marked unsafe.
352 unsafe {
353 let mut crash_ctx_msg: CrashContextMessage = std::mem::zeroed();
354 crash_ctx_msg.head.local_port = self.port;
355
356 let ret = msg::mach_msg(
357 ((&mut crash_ctx_msg.head) as *mut MachMsgHeader).cast(),
358 msg::MACH_RCV_MSG | msg::MACH_RCV_TIMEOUT,
359 0,
360 std::mem::size_of::<CrashContextMessage>() as u32,
361 self.port,
362 timeout.map(|t| t.as_millis() as u32).unwrap_or_default(),
363 port::MACH_PORT_NULL,
364 );
365
366 if ret == msg::MACH_RCV_TIMED_OUT {
367 return Ok(None);
368 } else if ret != msg::MACH_MSG_SUCCESS {
369 return Err(Error::Message(ret));
370 }
371
372 // Reconstruct a crash context from the message we received
373 let exception = if crash_ctx_msg.flags & FLAG_HAS_EXCEPTION != 0 {
374 Some(crate::ExceptionInfo {
375 kind: crash_ctx_msg.exception_kind,
376 code: crash_ctx_msg.exception_code,
377 subcode: (crash_ctx_msg.flags & FLAG_HAS_SUBCODE != 0)
378 .then_some(crash_ctx_msg.exception_subcode),
379 })
380 } else {
381 None
382 };
383
384 let crash_context = CrashContext {
385 task: crash_ctx_msg.task.name,
386 thread: crash_ctx_msg.crash_thread.name,
387 handler_thread: crash_ctx_msg.handler_thread.name,
388 exception,
389 };
390
391 // Translate the task to a pid so the user doesn't have to do it
392 // since there is not a binding available in libc/mach/mach2 for it
393 let mut pid = 0;
394 kern!(pid_for_task(crash_ctx_msg.task.name, &mut pid));
395 let ack_port = crash_ctx_msg.ack_port.name;
396
397 // Provide a way for the user to tell the client when they are done
398 // processing the crash context, unless the specified port was not
399 // set or somehow died immediately
400 let acker = Acknowledger {
401 port: (ack_port != port::MACH_PORT_DEAD && ack_port != port::MACH_PORT_NULL)
402 .then_some(ack_port),
403 };
404
405 Ok(Some(ReceivedCrashContext {
406 crash_context,
407 acker,
408 pid: pid as u32,
409 }))
410 }
411 }
412 }
413
414 impl Drop for Server {
415 fn drop(&mut self) {
416 // SAFETY: syscall
417 unsafe {
418 mach_port::mach_port_deallocate(mach_task_self(), self.port);
419 }
420 }
421 }
422
423 /// Used by a process running the [`Server`] to send a response back to the
424 /// [`Client`] that sent a [`CrashContext`] after it has finished
425 /// processing.
426 pub struct Acknowledger {
427 port: Option<port::mach_port_t>,
428 }
429
430 impl Acknowledger {
431 /// Sends an ack back to the client that sent a [`CrashContext`]
432 ///
433 /// # Errors
434 ///
435 /// We fail to send the ack to the port created in the [`Client`] process
436 pub fn send_ack(&mut self, ack: u32, timeout: Option<Duration>) -> Result<(), Error> {
437 if let Some(port) = self.port {
438 // SAFETY: syscalls. The caller has no invariants to uphold, so the
439 // entire function is not marked unsafe.
440 unsafe {
441 let mut msg = AcknowledgementMessage {
442 head: MachMsgHeader {
443 bits: msg::MACH_MSG_TYPE_COPY_SEND,
444 size: std::mem::size_of::<AcknowledgementMessage>() as u32,
445 remote_port: port,
446 local_port: port::MACH_PORT_NULL,
447 voucher_port: port::MACH_PORT_NULL,
448 id: 0,
449 },
450 result: ack,
451 };
452
453 // Try to actually send the message
454 msg!(msg::mach_msg(
455 ((&mut msg.head) as *mut MachMsgHeader).cast(),
456 msg::MACH_SEND_MSG | msg::MACH_SEND_TIMEOUT,
457 msg.head.size,
458 0,
459 port::MACH_PORT_NULL,
460 timeout.map(|t| t.as_millis() as u32).unwrap_or_default(),
461 port::MACH_PORT_NULL
462 ));
463
464 Ok(())
465 }
466 } else {
467 Ok(())
468 }
469 }
470 }
471
472 /// Used by [`Sender::send_crash_context`] to create a port to receive the
473 /// external process's response to sending a [`CrashContext`]
474 struct AckReceiver {
475 port: port::mach_port_t,
476 }
477
478 impl AckReceiver {
479 /// Allocates a new port to receive an ack from a [`Server`]
480 ///
481 /// # Errors
482 ///
483 /// We fail to allocate a port, or fail to add a send right to it.
484 ///
485 /// # Safety
486 ///
487 /// Performs syscalls. Only used internally hence the entire function being
488 /// marked unsafe.
489 unsafe fn new() -> Result<Self, Error> {
490 let mut port = 0;
491 kern!(mach_port::mach_port_allocate(
492 mach_task_self(),
493 port::MACH_PORT_RIGHT_RECEIVE,
494 &mut port
495 ));
496
497 kern!(mach_port::mach_port_insert_right(
498 mach_task_self(),
499 port,
500 port,
501 msg::MACH_MSG_TYPE_MAKE_SEND
502 ));
503
504 Ok(Self { port })
505 }
506
507 /// Waits for the specified duration to receive a result from the [`Server`]
508 /// that was sent a [`CrashContext`]
509 ///
510 /// # Errors
511 ///
512 /// We fail to receive an ack for some reason
513 ///
514 /// # Safety
515 ///
516 /// Performs syscalls. Only used internally hence the entire function being
517 /// marked unsafe.
518 unsafe fn recv_ack(&mut self, timeout: Option<Duration>) -> Result<u32, Error> {
519 let mut ack = AcknowledgementMessage {
520 head: MachMsgHeader {
521 bits: 0,
522 size: std::mem::size_of::<AcknowledgementMessage>() as u32,
523 remote_port: port::MACH_PORT_NULL,
524 local_port: self.port,
525 voucher_port: port::MACH_PORT_NULL,
526 id: 0,
527 },
528 result: 0,
529 };
530
531 // Wait for a response from the Server
532 msg!(msg::mach_msg(
533 ((&mut ack.head) as *mut MachMsgHeader).cast(),
534 msg::MACH_RCV_MSG | msg::MACH_RCV_TIMEOUT,
535 0,
536 ack.head.size,
537 self.port,
538 timeout.map(|t| t.as_millis() as u32).unwrap_or_default(),
539 port::MACH_PORT_NULL
540 ));
541
542 Ok(ack.result)
543 }
544 }
545
546 impl Drop for AckReceiver {
547 fn drop(&mut self) {
548 // SAFETY: syscall
549 unsafe {
550 mach_port::mach_port_deallocate(mach_task_self(), self.port);
551 }
552 }
553 }