Debian Codegraph @

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

raw
1 //! Contains types and helpers for dealing with `EXC_RESOURCE` exceptions.
2 //!
3 //! `EXC_RESOURCE` exceptions embed details about the resource and the limits
4 //! it exceeded within the `code` and, in some cases `subcode`, fields of the exception
5 //!
6 //! See <https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/osfmk/kern/exc_resource.h>
7 //! for the various constants and decoding of exception information wrapped in
8 //! this module.
9
10 use mach2::exception_types::EXC_RESOURCE;
11 use std::time::Duration;
12
13 /// The details for an `EXC_RESOURCE` exception as retrieved from the exception's
14 /// code and subcode
15 pub enum ResourceException {
16 /// This is sent by the kernel when the CPU usage monitor is tripped. Possibly fatal.
17 Cpu(CpuResourceException),
18 /// This is sent by the kernel when the platform idle wakeups monitor is tripped. Possibly fatal.
19 Wakeups(WakeupsResourceException),
20 /// This is sent by the kernel when a task crosses its high watermark memory limit. Never fatal at least on current MacOS versions.
21 Memory(MemoryResourceException),
22 /// This is sent by the kernel when a task crosses its I/O limits. Never fatal.
23 Io(IoResourceException),
24 /// This is sent by the kernel when a task crosses its thread limit. Always fatal.
25 Threads(ThreadsResourceException),
26 /// This is sent by the kernel when the process is leaking ipc ports and has
27 /// filled its port space. Always fatal.
28 Ports(PortsResourceException),
29 /// An unknown resource kind due to an addition to the set of possible
30 /// resource exception kinds in exc_resource.h
31 Unknown { kind: u8, flavor: u8 },
32 }
33
34 /// Each different resource exception type has 1 or more flavors that it can be,
35 /// and while these most likely don't change often, we try to be forward
36 /// compatible by not failing if a particular flavor is unknown
37 #[derive(Copy, Clone, Debug)]
38 pub enum Flavor<T: Copy + Clone + std::fmt::Debug> {
39 Known(T),
40 Unknown(u8),
41 }
42
43 impl<T: TryFrom<u8> + Copy + Clone + std::fmt::Debug> From<u64> for Flavor<T> {
44 #[inline]
45 fn from(code: u64) -> Self {
46 let flavor = resource_exc_flavor(code);
47 if let Ok(known) = T::try_from(flavor) {
48 Self::Known(known)
49 } else {
50 Self::Unknown(flavor)
51 }
52 }
53 }
54
55 impl<T: PartialEq + Copy + Clone + std::fmt::Debug> PartialEq<T> for Flavor<T> {
56 fn eq(&self, o: &T) -> bool {
57 match self {
58 Self::Known(flavor) => flavor == o,
59 Self::Unknown(_) => false,
60 }
61 }
62 }
63
64 /// Retrieves the resource exception kind from an exception code
65 #[inline]
66 pub fn resource_exc_kind(code: u64) -> u8 {
67 ((code >> 61) & 0x7) as u8
68 }
69
70 /// Retrieves the resource exception flavor from an exception code
71 #[inline]
72 pub fn resource_exc_flavor(code: u64) -> u8 {
73 ((code >> 58) & 0x7) as u8
74 }
75
76 impl super::ExceptionInfo {
77 /// If this is an `EXC_RESOURCE` exception, retrieves the exception metadata
78 /// from the code, otherwise returns `None`
79 pub fn resource_exception(&self) -> Option<ResourceException> {
80 if self.kind != EXC_RESOURCE {
81 return None;
82 }
83
84 let kind = resource_exc_kind(self.code);
85
86 let res_exc = if kind == ResourceKind::Cpu as u8 {
87 ResourceException::Cpu(CpuResourceException::from_exc_info(self.code, self.subcode))
88 } else if kind == ResourceKind::Wakeups as u8 {
89 ResourceException::Wakeups(WakeupsResourceException::from_exc_info(
90 self.code,
91 self.subcode,
92 ))
93 } else if kind == ResourceKind::Memory as u8 {
94 ResourceException::Memory(MemoryResourceException::from_exc_info(self.code))
95 } else if kind == ResourceKind::Io as u8 {
96 ResourceException::Io(IoResourceException::from_exc_info(self.code, self.subcode))
97 } else if kind == ResourceKind::Threads as u8 {
98 ResourceException::Threads(ThreadsResourceException::from_exc_info(self.code))
99 } else if kind == ResourceKind::Ports as u8 {
100 ResourceException::Ports(PortsResourceException::from_exc_info(self.code))
101 } else {
102 ResourceException::Unknown {
103 kind,
104 flavor: resource_exc_flavor(self.code),
105 }
106 };
107
108 Some(res_exc)
109 }
110 }
111
112 /// The types of resources that an `EXC_RESOURCE` exception can pertain to
113 #[repr(u8)]
114 pub enum ResourceKind {
115 Cpu = 1,
116 Wakeups = 2,
117 Memory = 3,
118 Io = 4,
119 Threads = 5,
120 Ports = 6,
121 }
122
123 /// The flavors for a [`CpuResourceException`]
124 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
125 #[repr(u8)]
126 pub enum CpuFlavor {
127 /// The process has surpassed its CPU limit
128 Monitor = 1,
129 /// The process has surpassed its CPU limit, and the process has been configured
130 /// to make this exception fatal
131 MonitorFatal = 2,
132 }
133
134 impl TryFrom<u8> for CpuFlavor {
135 type Error = ();
136
137 fn try_from(flavor: u8) -> Result<Self, Self::Error> {
138 match flavor {
139 1 => Ok(Self::Monitor),
140 2 => Ok(Self::MonitorFatal),
141 _ => Err(()),
142 }
143 }
144 }
145
146 /// These exceptions _may_ be fatal. They are not fatal by default at task
147 /// creation but can be made fatal by calling `proc_rlimit_control` with
148 /// `RLIMIT_CPU_USAGE_MONITOR` as the second argument and `CPUMON_MAKE_FATAL`
149 /// set in the flags. The flavor extracted from the exception code determines if
150 /// the exception is fatal.
151 ///
152 /// [Kernel code](https://github.com/apple-oss-distributions/xnu/blob/e7776783b89a353188416a9a346c6cdb4928faad/osfmk/kern/thread.c#L2475-L2616)
153 #[derive(Copy, Clone, Debug)]
154 pub struct CpuResourceException {
155 pub flavor: Flavor<CpuFlavor>,
156 /// If the exception is fatal. Currently only true if the flavor is [`CpuFlavor::MonitorFatal`]
157 pub is_fatal: bool,
158 /// The time period in which the CPU limit was surpassed
159 pub observation_interval: Duration,
160 /// The CPU % limit
161 pub limit: u8,
162 /// The CPU % consumed by the task
163 pub consumed: u8,
164 }
165
166 impl CpuResourceException {
167 /*
168 * code:
169 * +-----------------------------------------------+
170 * |[63:61] RESOURCE |[60:58] FLAVOR_CPU_ |[57:32] |
171 * |_TYPE_CPU |MONITOR[_FATAL] |Unused |
172 * +-----------------------------------------------+
173 * |[31:7] Interval (sec) | [6:0] CPU limit (%)|
174 * +-----------------------------------------------+
175 *
176 * subcode:
177 * +-----------------------------------------------+
178 * | | [6:0] % of CPU |
179 * | | actually consumed |
180 * +-----------------------------------------------+
181 *
182 */
183 #[inline]
184 pub fn from_exc_info(code: u64, subcode: Option<u64>) -> Self {
185 debug_assert_eq!(resource_exc_kind(code), ResourceKind::Cpu as u8);
186
187 let flavor = Flavor::from(code);
188 let interval_seconds = (code >> 7) & 0x1ffffff;
189 let limit = (code & 0x7f) as u8;
190 let consumed = subcode.map_or(0, |sc| sc & 0x7f) as u8;
191
192 // The default is that cpu resource exceptions are not fatal, so
193 // we only check the flavor against the (currently) one known value
194 // that indicates the exception is fatal
195 Self {
196 flavor,
197 is_fatal: flavor == CpuFlavor::MonitorFatal,
198 observation_interval: Duration::from_secs(interval_seconds),
199 limit,
200 consumed,
201 }
202 }
203 }
204
205 /// The flavors for a [`WakeupsResourceException`]
206 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
207 #[repr(u8)]
208 pub enum WakeupsFlavor {
209 Monitor = 1,
210 }
211
212 impl TryFrom<u8> for WakeupsFlavor {
213 type Error = ();
214
215 fn try_from(flavor: u8) -> Result<Self, Self::Error> {
216 match flavor {
217 1 => Ok(Self::Monitor),
218 _ => Err(()),
219 }
220 }
221 }
222
223 /// These exceptions may be fatal. They are not fatal by default at task
224 /// creation, but can be made fatal by calling `proc_rlimit_control` with
225 /// `RLIMIT_WAKEUPS_MONITOR` as the second argument and `WAKEMON_MAKE_FATAL`
226 /// set in the flags. Calling [`proc_get_wakemon_params`](https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/libsyscall/wrappers/libproc/libproc.c#L592-L608)
227 /// determines whether these exceptions are fatal.
228 ///
229 /// [Kernel source](https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/osfmk/kern/task.c#L7501-L7580)
230 pub struct WakeupsResourceException {
231 pub flavor: Flavor<WakeupsFlavor>,
232 /// The time period in which the number of wakeups was surpassed
233 pub observation_interval: Duration,
234 /// The number of wakeups permitted per second
235 pub permitted: u32,
236 /// The number of wakeups observed per second
237 pub observed: u32,
238 }
239
240 impl WakeupsResourceException {
241 /*
242 * code:
243 * +-----------------------------------------------+
244 * |[63:61] RESOURCE |[60:58] FLAVOR_ |[57:32] |
245 * |_TYPE_WAKEUPS |WAKEUPS_MONITOR |Unused |
246 * +-----------------------------------------------+
247 * | [31:20] Observation | [19:0] # of wakeups |
248 * | interval (sec) | permitted (per sec) |
249 * +-----------------------------------------------+
250 *
251 * subcode:
252 * +-----------------------------------------------+
253 * | | [19:0] # of wakeups |
254 * | | observed (per sec) |
255 * +-----------------------------------------------+
256 *
257 */
258 #[inline]
259 pub fn from_exc_info(code: u64, subcode: Option<u64>) -> Self {
260 debug_assert_eq!(resource_exc_kind(code), ResourceKind::Wakeups as u8);
261
262 let flavor = Flavor::from(code);
263 // Note that Apple has a bug in exc_resource.h where the masks in the
264 // decode macros for the interval and the permitted wakeups have been swapped
265 let interval_seconds = (code >> 20) & 0xfff;
266 let permitted = (code & 0xfffff) as u32;
267 let observed = subcode.map_or(0, |sc| sc & 0xfffff) as u32;
268
269 Self {
270 flavor,
271 observation_interval: Duration::from_secs(interval_seconds),
272 permitted,
273 observed,
274 }
275 }
276 }
277
278 /// The flavors for a [`MemoryResourceException`]
279 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
280 #[repr(u8)]
281 pub enum MemoryFlavor {
282 HighWatermark = 1,
283 }
284
285 impl TryFrom<u8> for MemoryFlavor {
286 type Error = ();
287
288 fn try_from(flavor: u8) -> Result<Self, Self::Error> {
289 match flavor {
290 1 => Ok(Self::HighWatermark),
291 _ => Err(()),
292 }
293 }
294 }
295
296 /// These exceptions, as of this writing, are never fatal.
297 ///
298 /// While memory exceptions _can_ be fatal, this appears to only be possible if
299 /// the kernel is built with `CONFIG_JETSAM` or in `DEVELOPMENT` or `DEBUG` modes,
300 /// so as of now, they should never be considered fatal, at least on `MacOS`
301 ///
302 /// [Kernel source](https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/osfmk/kern/task.c#L6767-L6874)
303 pub struct MemoryResourceException {
304 pub flavor: Flavor<MemoryFlavor>,
305 /// The limit in MiB of the high watermark
306 pub limit_mib: u16,
307 }
308
309 impl MemoryResourceException {
310 /*
311 * code:
312 * +------------------------------------------------+
313 * |[63:61] RESOURCE |[60:58] FLAVOR_HIGH_ |[57:32] |
314 * |_TYPE_MEMORY |WATERMARK |Unused |
315 * +------------------------------------------------+
316 * | | [12:0] HWM limit (MB)|
317 * +------------------------------------------------+
318 *
319 * subcode:
320 * +------------------------------------------------+
321 * | unused |
322 * +------------------------------------------------+
323 *
324 */
325 #[inline]
326 pub fn from_exc_info(code: u64) -> Self {
327 debug_assert_eq!(resource_exc_kind(code), ResourceKind::Memory as u8);
328
329 let flavor = Flavor::from(code);
330 let limit_mib = (code & 0x1fff) as u16;
331
332 Self { flavor, limit_mib }
333 }
334 }
335
336 /// The flavors for an [`IoResourceException`]
337 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
338 #[repr(u8)]
339 pub enum IoFlavor {
340 PhysicalWrites = 1,
341 LogicalWrites = 2,
342 }
343
344 impl TryFrom<u8> for IoFlavor {
345 type Error = ();
346
347 fn try_from(flavor: u8) -> Result<Self, Self::Error> {
348 match flavor {
349 1 => Ok(Self::PhysicalWrites),
350 2 => Ok(Self::LogicalWrites),
351 _ => Err(()),
352 }
353 }
354 }
355
356 /// These exceptions are never fatal.
357 ///
358 /// [Kernel source](https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/osfmk/kern/task.c#L7739-L7792)
359 pub struct IoResourceException {
360 pub flavor: Flavor<MemoryFlavor>,
361 /// The time period in which the I/O limit was surpassed
362 pub observation_interval: Duration,
363 /// The I/O limit in MiB of the high watermark
364 pub limit_mib: u16,
365 /// The observed I/O in MiB
366 pub observed_mib: u16,
367 }
368
369 impl IoResourceException {
370 /*
371 * code:
372 * +-----------------------------------------------+
373 * |[63:61] RESOURCE |[60:58] FLAVOR_IO_ |[57:32] |
374 * |_TYPE_IO |PHYSICAL/LOGICAL |Unused |
375 * +-----------------------------------------------+
376 * |[31:15] Interval (sec) | [14:0] Limit (MB) |
377 * +-----------------------------------------------+
378 *
379 * subcode:
380 * +-----------------------------------------------+
381 * | | [14:0] I/O Count |
382 * | | (in MB) |
383 * +-----------------------------------------------+
384 *
385 */
386 #[inline]
387 pub fn from_exc_info(code: u64, subcode: Option<u64>) -> Self {
388 debug_assert_eq!(resource_exc_kind(code), ResourceKind::Io as u8);
389
390 let flavor = Flavor::from(code);
391 let interval_seconds = (code >> 15) & 0x1ffff;
392 let limit_mib = (code & 0x7fff) as u16;
393 let observed_mib = subcode.map_or(0, |sc| sc & 0x7fff) as u16;
394
395 Self {
396 flavor,
397 observation_interval: Duration::from_secs(interval_seconds),
398 limit_mib,
399 observed_mib,
400 }
401 }
402 }
403
404 /// The flavors for a [`ThreadsResourceException`]
405 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
406 #[repr(u8)]
407 pub enum ThreadsFlavor {
408 HighWatermark = 1,
409 }
410
411 impl TryFrom<u8> for ThreadsFlavor {
412 type Error = ();
413
414 fn try_from(flavor: u8) -> Result<Self, Self::Error> {
415 match flavor {
416 1 => Ok(Self::HighWatermark),
417 _ => Err(()),
418 }
419 }
420 }
421
422 /// This exception is provided for completeness sake, but is only possible if
423 /// the kernel is built in `DEVELOPMENT` or `DEBUG` modes.
424 ///
425 /// [Kernel source](https://github.com/apple-oss-distributions/xnu/blob/e6231be02a03711ca404e5121a151b24afbff733/osfmk/kern/thread.c#L2575-L2620)
426 pub struct ThreadsResourceException {
427 pub flavor: Flavor<ThreadsFlavor>,
428 /// The thread limit
429 pub limit: u16,
430 }
431
432 impl ThreadsResourceException {
433 /*
434 * code:
435 * +--------------------------------------------------+
436 * |[63:61] RESOURCE |[60:58] FLAVOR_ |[57:32] |
437 * |_TYPE_THREADS |THREADS_HIGH_WATERMARK |Unused |
438 * +--------------------------------------------------+
439 * |[31:15] Unused | [14:0] Limit |
440 * +--------------------------------------------------+
441 *
442 * subcode:
443 * +-----------------------------------------------+
444 * | | Unused |
445 * | | |
446 * +-----------------------------------------------+
447 *
448 */
449 #[inline]
450 pub fn from_exc_info(code: u64) -> Self {
451 debug_assert_eq!(resource_exc_kind(code), ResourceKind::Threads as u8);
452
453 let flavor = Flavor::from(code);
454 let limit = (code & 0x7fff) as u16;
455
456 Self { flavor, limit }
457 }
458 }
459
460 /// The flavors for a [`PortsResourceException`]
461 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
462 #[repr(u8)]
463 pub enum PortsFlavor {
464 SpaceFull = 1,
465 }
466
467 impl TryFrom<u8> for PortsFlavor {
468 type Error = ();
469
470 fn try_from(flavor: u8) -> Result<Self, Self::Error> {
471 match flavor {
472 1 => Ok(Self::SpaceFull),
473 _ => Err(()),
474 }
475 }
476 }
477
478 /// This exception is always fatal, and in fact I'm unsure if this exception
479 /// is even observable, as the kernel will kill the offending process if
480 /// the port space is full
481 ///
482 /// [Kernel source](https://github.com/apple-oss-distributions/xnu/blob/e7776783b89a353188416a9a346c6cdb4928faad/osfmk/kern/task.c#L7907-L7969)
483 pub struct PortsResourceException {
484 pub flavor: Flavor<ThreadsFlavor>,
485 /// The number of allocated ports
486 pub allocated: u32,
487 }
488
489 impl PortsResourceException {
490 /*
491 * code:
492 * +-----------------------------------------------+
493 * |[63:61] RESOURCE |[60:58] FLAVOR_ |[57:32] |
494 * |_TYPE_PORTS |PORT_SPACE_FULL |Unused |
495 * +-----------------------------------------------+
496 * | [31:24] Unused | [23:0] # of ports |
497 * | | allocated |
498 * +-----------------------------------------------+
499 *
500 * subcode:
501 * +-----------------------------------------------+
502 * | | Unused |
503 * | | |
504 * +-----------------------------------------------+
505 *
506 */
507 #[inline]
508 pub fn from_exc_info(code: u64) -> Self {
509 debug_assert_eq!(resource_exc_kind(code), ResourceKind::Ports as u8);
510
511 let flavor = Flavor::from(code);
512 let allocated = (code & 0xffffff) as u32;
513
514 Self { flavor, allocated }
515 }
516 }