1 // Copyright 2015 The Crashpad Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "util/mach/exception_types.h"
16 
17 #include <Availability.h>
18 #include <AvailabilityMacros.h>
19 #include <dlfcn.h>
20 #include <errno.h>
21 #include <libproc.h>
22 #include <kern/exc_resource.h>
23 #include <strings.h>
24 
25 #include "base/logging.h"
26 #include "base/mac/mach_logging.h"
27 #include "util/mac/mac_util.h"
28 #include "util/mach/mach_extensions.h"
29 #include "util/numeric/in_range_cast.h"
30 
31 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
32 
33 extern "C" {
34 
35 // proc_get_wakemon_params() is present in the OS X 10.9 SDK, but no declaration
36 // is provided. This provides a declaration and marks it for weak import if the
37 // deployment target is below 10.9.
38 int proc_get_wakemon_params(pid_t pid, int* rate_hz, int* flags)
39     __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0);
40 
41 // Redeclare the method without the availability annotation to suppress the
42 // -Wpartial-availability warning.
43 int proc_get_wakemon_params(pid_t pid, int* rate_hz, int* flags);
44 
45 }  // extern "C"
46 
47 #else
48 
49 namespace {
50 
51 using ProcGetWakemonParamsType = int (*)(pid_t, int*, int*);
52 
53 // The SDK doesn’t have proc_get_wakemon_params() to link against, even with
54 // weak import. This function returns a function pointer to it if it exists at
55 // runtime, or nullptr if it doesn’t. proc_get_wakemon_params() is looked up in
56 // the same module that provides proc_pidinfo().
GetProcGetWakemonParams()57 ProcGetWakemonParamsType GetProcGetWakemonParams() {
58   Dl_info dl_info;
59   if (!dladdr(reinterpret_cast<void*>(proc_pidinfo), &dl_info)) {
60     return nullptr;
61   }
62 
63   void* dl_handle =
64       dlopen(dl_info.dli_fname, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
65   if (!dl_handle) {
66     return nullptr;
67   }
68 
69   ProcGetWakemonParamsType proc_get_wakemon_params =
70       reinterpret_cast<ProcGetWakemonParamsType>(
71           dlsym(dl_handle, "proc_get_wakemon_params"));
72   return proc_get_wakemon_params;
73 }
74 
75 }  // namespace
76 
77 #endif
78 
79 namespace {
80 
81 // Wraps proc_get_wakemon_params(), calling it if the system provides it. It’s
82 // present on OS X 10.9 and later. If it’s not available, sets errno to ENOSYS
83 // and returns -1.
ProcGetWakemonParams(pid_t pid,int * rate_hz,int * flags)84 int ProcGetWakemonParams(pid_t pid, int* rate_hz, int* flags) {
85 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
86   // proc_get_wakemon_params() isn’t in the SDK. Look it up dynamically.
87   static ProcGetWakemonParamsType proc_get_wakemon_params =
88       GetProcGetWakemonParams();
89 #endif
90 
91 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_9
92   // proc_get_wakemon_params() is definitely available if the deployment target
93   // is 10.9 or newer.
94   if (!proc_get_wakemon_params) {
95     errno = ENOSYS;
96     return -1;
97   }
98 #endif
99 
100   return proc_get_wakemon_params(pid, rate_hz, flags);
101 }
102 
103 }  // namespace
104 
105 namespace crashpad {
106 
ExcCrashRecoverOriginalException(mach_exception_code_t code_0,mach_exception_code_t * original_code_0,int * signal)107 exception_type_t ExcCrashRecoverOriginalException(
108     mach_exception_code_t code_0,
109     mach_exception_code_t* original_code_0,
110     int* signal) {
111   // 10.9.4 xnu-2422.110.17/bsd/kern/kern_exit.c proc_prepareexit() sets code[0]
112   // based on the signal value, original exception type, and low 20 bits of the
113   // original code[0] before calling xnu-2422.110.17/osfmk/kern/exception.c
114   // task_exception_notify() to raise an EXC_CRASH.
115   //
116   // The list of core-generating signals (as used in proc_prepareexit()’s call
117   // to hassigprop()) is in 10.9.4 xnu-2422.110.17/bsd/sys/signalvar.h sigprop:
118   // entires with SA_CORE are in the set. These signals are SIGQUIT, SIGILL,
119   // SIGTRAP, SIGABRT, SIGEMT, SIGFPE, SIGBUS, SIGSEGV, and SIGSYS. Processes
120   // killed for code-signing reasons will be killed by SIGKILL and are also
121   // eligible for EXC_CRASH handling, but processes killed by SIGKILL for other
122   // reasons are not.
123   if (signal) {
124     *signal = (code_0 >> 24) & 0xff;
125   }
126 
127   if (original_code_0) {
128     *original_code_0 = code_0 & 0xfffff;
129   }
130 
131   return (code_0 >> 20) & 0xf;
132 }
133 
ExcCrashCouldContainException(exception_type_t exception)134 bool ExcCrashCouldContainException(exception_type_t exception) {
135   // EXC_CRASH should never be wrapped in another EXC_CRASH.
136   //
137   // EXC_RESOURCE and EXC_GUARD are software exceptions that are never wrapped
138   // in EXC_CRASH. The only time EXC_CRASH is generated is for processes exiting
139   // due to an unhandled core-generating signal or being killed by SIGKILL for
140   // code-signing reasons. Neither of these apply to EXC_RESOURCE or EXC_GUARD.
141   // See 10.10 xnu-2782.1.97/bsd/kern/kern_exit.c proc_prepareexit(). Receiving
142   // these exception types wrapped in EXC_CRASH would lose information because
143   // their code[0] uses all 64 bits (see ExceptionSnapshotMac::Initialize()) and
144   // the code[0] recovered from EXC_CRASH only contains 20 significant bits.
145   //
146   // EXC_CORPSE_NOTIFY may be generated from EXC_CRASH, but the opposite should
147   // never occur.
148   //
149   // kMachExceptionSimulated is a non-fatal Crashpad-specific pseudo-exception
150   // that never exists as an exception within the kernel and should thus never
151   // be wrapped in EXC_CRASH.
152   return exception != EXC_CRASH &&
153          exception != EXC_RESOURCE &&
154          exception != EXC_GUARD &&
155          exception != EXC_CORPSE_NOTIFY &&
156          exception != kMachExceptionSimulated;
157 }
158 
ExceptionCodeForMetrics(exception_type_t exception,mach_exception_code_t code_0)159 int32_t ExceptionCodeForMetrics(exception_type_t exception,
160                                 mach_exception_code_t code_0) {
161   if (exception == kMachExceptionSimulated) {
162     return exception;
163   }
164 
165   int signal = 0;
166   if (exception == EXC_CRASH) {
167     const exception_type_t original_exception =
168         ExcCrashRecoverOriginalException(code_0, &code_0, &signal);
169     if (!ExcCrashCouldContainException(original_exception)) {
170       LOG(WARNING) << "EXC_CRASH should not contain exception "
171                    << original_exception;
172       return InRangeCast<uint16_t>(original_exception, 0xffff) << 16;
173     }
174     exception = original_exception;
175   }
176 
177   uint16_t metrics_exception = InRangeCast<uint16_t>(exception, 0xffff);
178 
179   uint16_t metrics_code_0;
180   switch (exception) {
181     case EXC_RESOURCE:
182       metrics_code_0 = (EXC_RESOURCE_DECODE_RESOURCE_TYPE(code_0) << 8) |
183                        EXC_RESOURCE_DECODE_FLAVOR(code_0);
184       break;
185 
186     case EXC_GUARD: {
187       // This will be GUARD_TYPE_MACH_PORT (1) from <mach/port.h> or
188       // GUARD_TYPE_FD (2) from 10.12.2 xnu-3789.31.2/bsd/sys/guarded.h
189       const uint8_t guard_type = (code_0) >> 61;
190 
191       // These exceptions come through 10.12.2
192       // xnu-3789.31.2/osfmk/ipc/mach_port.c mach_port_guard_exception() or
193       // xnu-3789.31.2/bsd/kern/kern_guarded.c fp_guard_exception(). In each
194       // case, bits 32-60 of code_0 encode the guard type-specific “flavor”. For
195       // Mach port guards, these flavor codes come from the
196       // mach_port_guard_exception_codes enum in <mach/port.h>. For file
197       // descriptor guards, they come from the guard_exception_codes enum in
198       // xnu-3789.31.2/bsd/sys/guarded.h. Both of these enums define shifted-bit
199       // values (1 << 0, 1 << 1, 1 << 2, etc.) In actual usage as determined by
200       // callers to these functions, these “flavor” codes are never ORed with
201       // one another. For the purposes of encoding these codes for metrics,
202       // convert the flavor codes to their corresponding bit shift values.
203       const uint32_t guard_flavor = (code_0 >> 32) & 0x1fffffff;
204       const int first_bit = ffs(guard_flavor);
205       uint8_t metrics_guard_flavor;
206       if (first_bit) {
207         metrics_guard_flavor = first_bit - 1;
208 
209         const uint32_t test_guard_flavor = 1 << metrics_guard_flavor;
210         if (guard_flavor != test_guard_flavor) {
211           // Another bit is set.
212           DCHECK_EQ(guard_flavor, test_guard_flavor);
213           metrics_guard_flavor = 0xff;
214         }
215       } else {
216         metrics_guard_flavor = 0xff;
217       }
218 
219       metrics_code_0 = (guard_type << 8) | metrics_guard_flavor;
220       break;
221     }
222 
223     case EXC_CORPSE_NOTIFY:
224       // code_0 may be a pointer. See 10.12.2 xnu-3789.31.2/osfmk/kern/task.c
225       // task_deliver_crash_notification(). Just encode 0 for metrics purposes.
226       metrics_code_0 = 0;
227       break;
228 
229     default:
230       metrics_code_0 = InRangeCast<uint16_t>(code_0, 0xffff);
231       if (exception == 0 && metrics_code_0 == 0 && signal != 0) {
232         // This exception came from a signal that did not originate as another
233         // Mach exception. Encode the signal number, using EXC_CRASH as the
234         // top-level exception type. This is safe because EXC_CRASH will not
235         // otherwise appear as metrics_exception.
236         metrics_exception = EXC_CRASH;
237         metrics_code_0 = signal;
238       }
239       break;
240   }
241 
242   return (metrics_exception << 16) | metrics_code_0;
243 }
244 
IsExceptionNonfatalResource(exception_type_t exception,mach_exception_code_t code_0,pid_t pid)245 bool IsExceptionNonfatalResource(exception_type_t exception,
246                                  mach_exception_code_t code_0,
247                                  pid_t pid) {
248   if (exception != EXC_RESOURCE) {
249     return false;
250   }
251 
252   const int resource_type = EXC_RESOURCE_DECODE_RESOURCE_TYPE(code_0);
253   const int resource_flavor = EXC_RESOURCE_DECODE_FLAVOR(code_0);
254 
255   if (resource_type == RESOURCE_TYPE_CPU &&
256       (resource_flavor == FLAVOR_CPU_MONITOR ||
257        resource_flavor == FLAVOR_CPU_MONITOR_FATAL)) {
258     // These exceptions may be fatal. They are not fatal by default at task
259     // creation but can be made fatal by calling proc_rlimit_control() with
260     // RLIMIT_CPU_USAGE_MONITOR as the second argument and CPUMON_MAKE_FATAL set
261     // in the flags.
262     if (MacOSXMinorVersion() >= 10) {
263       // In OS X 10.10, the exception code indicates whether the exception is
264       // fatal. See 10.10 xnu-2782.1.97/osfmk/kern/thread.c
265       // THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU__SENDING_EXC_RESOURCE().
266       return resource_flavor == FLAVOR_CPU_MONITOR;
267     }
268 
269     // In OS X 10.9, there’s no way to determine whether the exception is fatal.
270     // Unlike RESOURCE_TYPE_WAKEUPS below, there’s no way to determine this
271     // outside the kernel. proc_rlimit_control()’s RLIMIT_CPU_USAGE_MONITOR is
272     // the only interface to modify CPUMON_MAKE_FATAL, but it’s only able to set
273     // this bit, not obtain its current value.
274     //
275     // Default to assuming that these exceptions are nonfatal. They are nonfatal
276     // by default and no users of proc_rlimit_control() were found on 10.9.5
277     // 13F1066 in /System and /usr outside of Metadata.framework and associated
278     // tools.
279     return true;
280   }
281 
282   if (resource_type == RESOURCE_TYPE_WAKEUPS &&
283       resource_flavor == FLAVOR_WAKEUPS_MONITOR) {
284     // These exceptions may be fatal. They are not fatal by default at task
285     // creation, but can be made fatal by calling proc_rlimit_control() with
286     // RLIMIT_WAKEUPS_MONITOR as the second argument and WAKEMON_MAKE_FATAL set
287     // in the flags.
288     //
289     // proc_get_wakemon_params() (which calls
290     // through to proc_rlimit_control() with RLIMIT_WAKEUPS_MONITOR) determines
291     // whether these exceptions are fatal. See 10.10
292     // xnu-2782.1.97/osfmk/kern/task.c
293     // THIS_PROCESS_IS_CAUSING_TOO_MANY_WAKEUPS__SENDING_EXC_RESOURCE().
294     //
295     // If proc_get_wakemon_params() fails, default to assuming that these
296     // exceptions are nonfatal. They are nonfatal by default and no users of
297     // proc_rlimit_control() were found on 10.9.5 13F1066 in /System and /usr
298     // outside of Metadata.framework and associated tools.
299     int wm_rate;
300     int wm_flags;
301     int rv = ProcGetWakemonParams(pid, &wm_rate, &wm_flags);
302     if (rv < 0) {
303       PLOG(WARNING) << "ProcGetWakemonParams";
304       return true;
305     }
306 
307     return !(wm_flags & WAKEMON_MAKE_FATAL);
308   }
309 
310   if (resource_type == RESOURCE_TYPE_MEMORY &&
311       resource_flavor == FLAVOR_HIGH_WATERMARK) {
312     // These exceptions were never fatal prior to 10.12. See 10.10
313     // xnu-2782.1.97/osfmk/kern/task.c
314     // THIS_PROCESS_CROSSED_HIGH_WATERMARK__SENDING_EXC_RESOURCE().
315     //
316     // A superficial examination of 10.12 shows that these exceptions may be
317     // fatal, as determined by the P_MEMSTAT_FATAL_MEMLIMIT bit of the
318     // kernel-internal struct proc::p_memstat_state. See 10.12.3
319     // xnu-3789.41.3/osfmk/kern/task.c task_footprint_exceeded(). This bit is
320     // not exposed to user space, which makes it difficult to determine whether
321     // the kernel considers a given instance of this exception fatal. However, a
322     // close read reveals that it is only possible for this bit to become set
323     // when xnu-3789.41.3/bsd/kern/kern_memorystatus.c
324     // memorystatus_cmd_set_memlimit_properties() is called, which is only
325     // possible when the kernel is built with CONFIG_JETSAM set, or if the
326     // kern.memorystatus_highwater_enabled sysctl is used, which is only
327     // possible when the kernel is built with DEVELOPMENT or DEBUG set. Although
328     // CONFIG_JETSAM is used on iOS, it is not used on macOS. DEVELOPMENT and
329     // DEBUG are also not set for production kernels. It therefore remains
330     // impossible for these exceptions to be fatal, even on 10.12.
331     return true;
332   }
333 
334   if (resource_type == RESOURCE_TYPE_IO) {
335     // These exceptions are never fatal. See 10.12.3
336     // xnu-3789.41.3/osfmk/kern/task.c
337     // SENDING_NOTIFICATION__THIS_PROCESS_IS_CAUSING_TOO_MUCH_IO().
338     return true;
339   }
340 
341   // Treat unknown exceptions as fatal. This is the conservative approach: it
342   // may result in more crash reports being generated, but the type-flavor
343   // combinations can be evaluated to determine appropriate handling.
344   LOG(WARNING) << "unknown resource type " << resource_type << " flavor "
345                << resource_flavor;
346   return false;
347 }
348 
349 }  // namespace crashpad
350