1 //===-- MachException.cpp ---------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Created by Greg Clayton on 6/18/07.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MachException.h"
15 #include "DNB.h"
16 #include "DNBError.h"
17 #include "DNBLog.h"
18 #include "MachProcess.h"
19 #include "PThreadMutex.h"
20 #include "SysSignal.h"
21 #include <errno.h>
22 #include <sys/ptrace.h>
23 #include <sys/types.h>
24 
25 // Routine mach_exception_raise
26 extern "C" kern_return_t
27 catch_mach_exception_raise(mach_port_t exception_port, mach_port_t thread,
28                            mach_port_t task, exception_type_t exception,
29                            mach_exception_data_t code,
30                            mach_msg_type_number_t codeCnt);
31 
32 extern "C" kern_return_t catch_mach_exception_raise_state(
33     mach_port_t exception_port, exception_type_t exception,
34     const mach_exception_data_t code, mach_msg_type_number_t codeCnt,
35     int *flavor, const thread_state_t old_state,
36     mach_msg_type_number_t old_stateCnt, thread_state_t new_state,
37     mach_msg_type_number_t *new_stateCnt);
38 
39 // Routine mach_exception_raise_state_identity
40 extern "C" kern_return_t catch_mach_exception_raise_state_identity(
41     mach_port_t exception_port, mach_port_t thread, mach_port_t task,
42     exception_type_t exception, mach_exception_data_t code,
43     mach_msg_type_number_t codeCnt, int *flavor, thread_state_t old_state,
44     mach_msg_type_number_t old_stateCnt, thread_state_t new_state,
45     mach_msg_type_number_t *new_stateCnt);
46 
47 extern "C" boolean_t mach_exc_server(mach_msg_header_t *InHeadP,
48                                      mach_msg_header_t *OutHeadP);
49 
50 // Note: g_message points to the storage allocated to catch the data from
51 // catching the current exception raise. It's populated when we catch a raised
52 // exception which can't immediately be replied to.
53 //
54 // If it becomes possible to catch exceptions from multiple threads
55 // simultaneously, accesses to g_message would need to be mutually exclusive.
56 static MachException::Data *g_message = NULL;
57 
58 extern "C" kern_return_t catch_mach_exception_raise_state(
59     mach_port_t exc_port, exception_type_t exc_type,
60     const mach_exception_data_t exc_data, mach_msg_type_number_t exc_data_count,
61     int *flavor, const thread_state_t old_state,
62     mach_msg_type_number_t old_stateCnt, thread_state_t new_state,
63     mach_msg_type_number_t *new_stateCnt) {
64   if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) {
65     DNBLogThreaded("::%s ( exc_port = 0x%4.4x, exc_type = %d ( %s ), exc_data "
66                    "= 0x%llx, exc_data_count = %d)",
67                    __FUNCTION__, exc_port, exc_type,
68                    MachException::Name(exc_type), (uint64_t)exc_data,
69                    exc_data_count);
70   }
71   return KERN_FAILURE;
72 }
73 
74 extern "C" kern_return_t catch_mach_exception_raise_state_identity(
75     mach_port_t exc_port, mach_port_t thread_port, mach_port_t task_port,
76     exception_type_t exc_type, mach_exception_data_t exc_data,
77     mach_msg_type_number_t exc_data_count, int *flavor,
78     thread_state_t old_state, mach_msg_type_number_t old_stateCnt,
79     thread_state_t new_state, mach_msg_type_number_t *new_stateCnt) {
80   if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) {
81     DNBLogThreaded("::%s ( exc_port = 0x%4.4x, thd_port = 0x%4.4x, tsk_port = "
82                    "0x%4.4x, exc_type = %d ( %s ), exc_data[%d] = { 0x%llx, "
83                    "0x%llx })",
84                    __FUNCTION__, exc_port, thread_port, task_port, exc_type,
85                    MachException::Name(exc_type), exc_data_count,
86                    (uint64_t)(exc_data_count > 0 ? exc_data[0] : 0xBADDBADD),
87                    (uint64_t)(exc_data_count > 1 ? exc_data[1] : 0xBADDBADD));
88   }
89   mach_port_deallocate(mach_task_self(), task_port);
90   mach_port_deallocate(mach_task_self(), thread_port);
91 
92   return KERN_FAILURE;
93 }
94 
95 extern "C" kern_return_t
96 catch_mach_exception_raise(mach_port_t exc_port, mach_port_t thread_port,
97                            mach_port_t task_port, exception_type_t exc_type,
98                            mach_exception_data_t exc_data,
99                            mach_msg_type_number_t exc_data_count) {
100   if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) {
101     DNBLogThreaded("::%s ( exc_port = 0x%4.4x, thd_port = 0x%4.4x, tsk_port = "
102                    "0x%4.4x, exc_type = %d ( %s ), exc_data[%d] = { 0x%llx, "
103                    "0x%llx })",
104                    __FUNCTION__, exc_port, thread_port, task_port, exc_type,
105                    MachException::Name(exc_type), exc_data_count,
106                    (uint64_t)(exc_data_count > 0 ? exc_data[0] : 0xBADDBADD),
107                    (uint64_t)(exc_data_count > 1 ? exc_data[1] : 0xBADDBADD));
108   }
109   g_message->exc_type = 0;
110   g_message->exc_data.clear();
111 
112   if (task_port == g_message->task_port) {
113     g_message->task_port = task_port;
114     g_message->thread_port = thread_port;
115     g_message->exc_type = exc_type;
116     for (mach_msg_type_number_t i=0; i<exc_data_count; ++i)
117       g_message->exc_data.push_back(exc_data[i]);
118     return KERN_SUCCESS;
119   } else if (!MachTask::IsValid(g_message->task_port)) {
120     // Our original exception port isn't valid anymore check for a SIGTRAP
121     if (exc_type == EXC_SOFTWARE && exc_data_count == 2 &&
122         exc_data[0] == EXC_SOFT_SIGNAL && exc_data[1] == SIGTRAP) {
123       // We got a SIGTRAP which indicates we might have exec'ed and possibly
124       // lost our old task port during the exec, so we just need to switch over
125       // to using this new task port
126       g_message->task_port = task_port;
127       g_message->thread_port = thread_port;
128       g_message->exc_type = exc_type;
129       for (mach_msg_type_number_t i=0; i<exc_data_count; ++i)
130         g_message->exc_data.push_back(exc_data[i]);
131       return KERN_SUCCESS;
132     }
133   }
134   return KERN_FAILURE;
135 }
136 
137 void MachException::Message::Dump() const {
138   DNBLogThreadedIf(LOG_EXCEPTIONS, "  exc_msg { bits = 0x%8.8x size = 0x%8.8x "
139                                    "remote-port = 0x%8.8x local-port = 0x%8.8x "
140                                    "reserved = 0x%8.8x id = 0x%8.8x } ",
141                    exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
142                    exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
143                    exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id);
144 
145   DNBLogThreadedIf(LOG_EXCEPTIONS, "reply_msg { bits = 0x%8.8x size = 0x%8.8x "
146                                    "remote-port = 0x%8.8x local-port = 0x%8.8x "
147                                    "reserved = 0x%8.8x id = 0x%8.8x }",
148                    reply_msg.hdr.msgh_bits, reply_msg.hdr.msgh_size,
149                    reply_msg.hdr.msgh_remote_port,
150                    reply_msg.hdr.msgh_local_port, reply_msg.hdr.msgh_reserved,
151                    reply_msg.hdr.msgh_id);
152 
153   state.Dump();
154 }
155 
156 bool MachException::Data::GetStopInfo(
157     struct DNBThreadStopInfo *stop_info) const {
158   // Zero out the structure.
159   memset(stop_info, 0, sizeof(struct DNBThreadStopInfo));
160 
161   if (exc_type == 0) {
162     stop_info->reason = eStopTypeInvalid;
163     return true;
164   }
165 
166   // We always stop with a mach exceptions
167   stop_info->reason = eStopTypeException;
168   // Save the EXC_XXXX exception type
169   stop_info->details.exception.type = exc_type;
170 
171   // Fill in a text description
172   const char *exc_name = MachException::Name(exc_type);
173   char *desc = stop_info->description;
174   const char *end_desc = desc + DNB_THREAD_STOP_INFO_MAX_DESC_LENGTH;
175   if (exc_name)
176     desc +=
177         snprintf(desc, DNB_THREAD_STOP_INFO_MAX_DESC_LENGTH, "%s", exc_name);
178   else
179     desc +=
180         snprintf(desc, DNB_THREAD_STOP_INFO_MAX_DESC_LENGTH, "%i", exc_type);
181 
182   stop_info->details.exception.data_count = exc_data.size();
183 
184   int soft_signal = SoftSignal();
185   if (soft_signal) {
186     if (desc < end_desc) {
187       const char *sig_str = SysSignal::Name(soft_signal);
188       snprintf(desc, end_desc - desc, " EXC_SOFT_SIGNAL( %i ( %s ))",
189                soft_signal, sig_str ? sig_str : "unknown signal");
190     }
191   } else {
192     // No special disassembly for exception data, just
193     size_t idx;
194     if (desc < end_desc) {
195       desc += snprintf(desc, end_desc - desc, " data[%llu] = {",
196                        (uint64_t)stop_info->details.exception.data_count);
197 
198       for (idx = 0;
199            desc < end_desc && idx < stop_info->details.exception.data_count;
200            ++idx)
201         desc += snprintf(
202             desc, end_desc - desc, "0x%llx%c", (uint64_t)exc_data[idx],
203             ((idx + 1 == stop_info->details.exception.data_count) ? '}' : ','));
204     }
205   }
206 
207   // Copy the exception data
208   size_t i;
209   for (i = 0; i < stop_info->details.exception.data_count; i++)
210     stop_info->details.exception.data[i] = exc_data[i];
211 
212   return true;
213 }
214 
215 void MachException::Data::DumpStopReason() const {
216   int soft_signal = SoftSignal();
217   if (soft_signal) {
218     const char *signal_str = SysSignal::Name(soft_signal);
219     if (signal_str)
220       DNBLog("signal(%s)", signal_str);
221     else
222       DNBLog("signal(%i)", soft_signal);
223     return;
224   }
225   DNBLog("%s", Name(exc_type));
226 }
227 
228 kern_return_t MachException::Message::Receive(mach_port_t port,
229                                               mach_msg_option_t options,
230                                               mach_msg_timeout_t timeout,
231                                               mach_port_t notify_port) {
232   DNBError err;
233   const bool log_exceptions = DNBLogCheckLogBit(LOG_EXCEPTIONS);
234   mach_msg_timeout_t mach_msg_timeout =
235       options & MACH_RCV_TIMEOUT ? timeout : 0;
236   if (log_exceptions && ((options & MACH_RCV_TIMEOUT) == 0)) {
237     // Dump this log message if we have no timeout in case it never returns
238     DNBLogThreaded("::mach_msg ( msg->{bits = %#x, size = %u remote_port = "
239                    "%#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, option "
240                    "= %#x, send_size = 0, rcv_size = %llu, rcv_name = %#x, "
241                    "timeout = %u, notify = %#x)",
242                    exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
243                    exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
244                    exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id, options,
245                    (uint64_t)sizeof(exc_msg.data), port, mach_msg_timeout,
246                    notify_port);
247   }
248 
249   err = ::mach_msg(&exc_msg.hdr,
250                    options,              // options
251                    0,                    // Send size
252                    sizeof(exc_msg.data), // Receive size
253                    port,             // exception port to watch for exception on
254                    mach_msg_timeout, // timeout in msec (obeyed only if
255                                      // MACH_RCV_TIMEOUT is ORed into the
256                                      // options parameter)
257                    notify_port);
258 
259   // Dump any errors we get
260   if (log_exceptions) {
261     err.LogThreaded("::mach_msg ( msg->{bits = %#x, size = %u remote_port = "
262                     "%#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, "
263                     "option = %#x, send_size = %u, rcv_size = %u, rcv_name = "
264                     "%#x, timeout = %u, notify = %#x)",
265                     exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
266                     exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
267                     exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id, options, 0,
268                     sizeof(exc_msg.data), port, mach_msg_timeout, notify_port);
269   }
270   return err.Status();
271 }
272 
273 bool MachException::Message::CatchExceptionRaise(task_t task) {
274   bool success = false;
275   state.task_port = task;
276   g_message = &state;
277   // The exc_server function is the MIG generated server handling function
278   // to handle messages from the kernel relating to the occurrence of an
279   // exception in a thread. Such messages are delivered to the exception port
280   // set via thread_set_exception_ports or task_set_exception_ports. When an
281   // exception occurs in a thread, the thread sends an exception message to
282   // its exception port, blocking in the kernel waiting for the receipt of a
283   // reply. The exc_server function performs all necessary argument handling
284   // for this kernel message and calls catch_exception_raise,
285   // catch_exception_raise_state or catch_exception_raise_state_identity,
286   // which should handle the exception. If the called routine returns
287   // KERN_SUCCESS, a reply message will be sent, allowing the thread to
288   // continue from the point of the exception; otherwise, no reply message
289   // is sent and the called routine must have dealt with the exception
290   // thread directly.
291   if (mach_exc_server(&exc_msg.hdr, &reply_msg.hdr)) {
292     success = true;
293   } else if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) {
294     DNBLogThreaded("mach_exc_server returned zero...");
295   }
296   g_message = NULL;
297   return success;
298 }
299 
300 kern_return_t MachException::Message::Reply(MachProcess *process, int signal) {
301   // Reply to the exception...
302   DNBError err;
303 
304   // If we had a soft signal, we need to update the thread first so it can
305   // continue without signaling
306   int soft_signal = state.SoftSignal();
307   if (soft_signal) {
308     int state_pid = -1;
309     if (process->Task().TaskPort() == state.task_port) {
310       // This is our task, so we can update the signal to send to it
311       state_pid = process->ProcessID();
312       soft_signal = signal;
313     } else {
314       err = ::pid_for_task(state.task_port, &state_pid);
315     }
316 
317     assert(state_pid != -1);
318     if (state_pid != -1) {
319       errno = 0;
320       if (::ptrace(PT_THUPDATE, state_pid,
321                    (caddr_t)((uintptr_t)state.thread_port), soft_signal) != 0)
322         err.SetError(errno, DNBError::POSIX);
323       else
324         err.Clear();
325 
326       if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
327         err.LogThreaded("::ptrace (request = PT_THUPDATE, pid = 0x%4.4x, tid = "
328                         "0x%4.4x, signal = %i)",
329                         state_pid, state.thread_port, soft_signal);
330     }
331   }
332 
333   DNBLogThreadedIf(
334       LOG_EXCEPTIONS, "::mach_msg ( msg->{bits = %#x, size = %u, remote_port = "
335                       "%#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, "
336                       "option = %#x, send_size = %u, rcv_size = %u, rcv_name = "
337                       "%#x, timeout = %u, notify = %#x)",
338       reply_msg.hdr.msgh_bits, reply_msg.hdr.msgh_size,
339       reply_msg.hdr.msgh_remote_port, reply_msg.hdr.msgh_local_port,
340       reply_msg.hdr.msgh_reserved, reply_msg.hdr.msgh_id,
341       MACH_SEND_MSG | MACH_SEND_INTERRUPT, reply_msg.hdr.msgh_size, 0,
342       MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
343 
344   err = ::mach_msg(&reply_msg.hdr, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
345                    reply_msg.hdr.msgh_size, 0, MACH_PORT_NULL,
346                    MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
347 
348   if (err.Fail()) {
349     if (err.Status() == MACH_SEND_INTERRUPTED) {
350       if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
351         err.LogThreaded("::mach_msg() - send interrupted");
352       // TODO: keep retrying to reply???
353     } else {
354       if (state.task_port == process->Task().TaskPort()) {
355         DNBLogThreaded("error: mach_msg() returned an error when replying to a "
356                        "mach exception: error = %u",
357                        err.Status());
358       } else {
359         if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
360           err.LogThreaded("::mach_msg() - failed (child of task)");
361       }
362     }
363   }
364 
365   return err.Status();
366 }
367 
368 void MachException::Data::Dump() const {
369   const char *exc_type_name = MachException::Name(exc_type);
370   DNBLogThreadedIf(
371       LOG_EXCEPTIONS, "    state { task_port = 0x%4.4x, thread_port =  "
372                       "0x%4.4x, exc_type = %i (%s) ...",
373       task_port, thread_port, exc_type, exc_type_name ? exc_type_name : "???");
374 
375   const size_t exc_data_count = exc_data.size();
376   // Dump any special exception data contents
377   int soft_signal = SoftSignal();
378   if (soft_signal != 0) {
379     const char *sig_str = SysSignal::Name(soft_signal);
380     DNBLogThreadedIf(LOG_EXCEPTIONS,
381                      "            exc_data: EXC_SOFT_SIGNAL (%i (%s))",
382                      soft_signal, sig_str ? sig_str : "unknown signal");
383   } else {
384     // No special disassembly for this data, just dump the data
385     size_t idx;
386     for (idx = 0; idx < exc_data_count; ++idx) {
387       DNBLogThreadedIf(LOG_EXCEPTIONS, "            exc_data[%llu]: 0x%llx",
388                        (uint64_t)idx, (uint64_t)exc_data[idx]);
389     }
390   }
391 }
392 
393 #define PREV_EXC_MASK_ALL                                                      \
394   (EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC |      \
395    EXC_MASK_EMULATION | EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT |              \
396    EXC_MASK_SYSCALL | EXC_MASK_MACH_SYSCALL | EXC_MASK_RPC_ALERT |             \
397    EXC_MASK_MACHINE)
398 
399 // Don't listen for EXC_RESOURCE, it should really get handled by the system
400 // handler.
401 
402 #ifndef EXC_RESOURCE
403 #define EXC_RESOURCE 11
404 #endif
405 
406 #ifndef EXC_MASK_RESOURCE
407 #define EXC_MASK_RESOURCE (1 << EXC_RESOURCE)
408 #endif
409 
410 #define LLDB_EXC_MASK (EXC_MASK_ALL & ~EXC_MASK_RESOURCE)
411 
412 kern_return_t MachException::PortInfo::Save(task_t task) {
413   DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE,
414                    "MachException::PortInfo::Save ( task = 0x%4.4x )", task);
415   // Be careful to be able to have debugserver built on a newer OS than what
416   // it is currently running on by being able to start with all exceptions
417   // and back off to just what is supported on the current system
418   DNBError err;
419 
420   mask = LLDB_EXC_MASK;
421 
422   count = (sizeof(ports) / sizeof(ports[0]));
423   err = ::task_get_exception_ports(task, mask, masks, &count, ports, behaviors,
424                                    flavors);
425   if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
426     err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = 0x%x, "
427                     "maskCnt => %u, ports, behaviors, flavors )",
428                     task, mask, count);
429 
430   if (err.Status() == KERN_INVALID_ARGUMENT && mask != PREV_EXC_MASK_ALL) {
431     mask = PREV_EXC_MASK_ALL;
432     count = (sizeof(ports) / sizeof(ports[0]));
433     err = ::task_get_exception_ports(task, mask, masks, &count, ports,
434                                      behaviors, flavors);
435     if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
436       err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = "
437                       "0x%x, maskCnt => %u, ports, behaviors, flavors )",
438                       task, mask, count);
439   }
440   if (err.Fail()) {
441     mask = 0;
442     count = 0;
443   }
444   return err.Status();
445 }
446 
447 kern_return_t MachException::PortInfo::Restore(task_t task) {
448   DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE,
449                    "MachException::PortInfo::Restore( task = 0x%4.4x )", task);
450   uint32_t i = 0;
451   DNBError err;
452   if (count > 0) {
453     for (i = 0; i < count; i++) {
454       err = ::task_set_exception_ports(task, masks[i], ports[i], behaviors[i],
455                                        flavors[i]);
456       if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
457         err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
458                         "exception_mask = 0x%8.8x, new_port = 0x%4.4x, "
459                         "behavior = 0x%8.8x, new_flavor = 0x%8.8x )",
460                         task, masks[i], ports[i], behaviors[i], flavors[i]);
461         // Bail if we encounter any errors
462       }
463 
464       if (err.Fail())
465         break;
466     }
467   }
468   count = 0;
469   return err.Status();
470 }
471 
472 const char *MachException::Name(exception_type_t exc_type) {
473   switch (exc_type) {
474   case EXC_BAD_ACCESS:
475     return "EXC_BAD_ACCESS";
476   case EXC_BAD_INSTRUCTION:
477     return "EXC_BAD_INSTRUCTION";
478   case EXC_ARITHMETIC:
479     return "EXC_ARITHMETIC";
480   case EXC_EMULATION:
481     return "EXC_EMULATION";
482   case EXC_SOFTWARE:
483     return "EXC_SOFTWARE";
484   case EXC_BREAKPOINT:
485     return "EXC_BREAKPOINT";
486   case EXC_SYSCALL:
487     return "EXC_SYSCALL";
488   case EXC_MACH_SYSCALL:
489     return "EXC_MACH_SYSCALL";
490   case EXC_RPC_ALERT:
491     return "EXC_RPC_ALERT";
492 #ifdef EXC_CRASH
493   case EXC_CRASH:
494     return "EXC_CRASH";
495 #endif
496   default:
497     break;
498   }
499   return NULL;
500 }
501