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 // Any access to the g_message variable should be done by locking the
51 // g_message_mutex first, using the g_message variable, then unlocking
52 // the g_message_mutex. See MachException::Message::CatchExceptionRaise()
53 // for sample code.
54 
55 static MachException::Data *g_message = NULL;
56 // static pthread_mutex_t g_message_mutex = PTHREAD_MUTEX_INITIALIZER;
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.Error();
271 }
272 
273 bool MachException::Message::CatchExceptionRaise(task_t task) {
274   bool success = false;
275   // locker will keep a mutex locked until it goes out of scope
276   //    PThreadMutex::Locker locker(&g_message_mutex);
277   //    DNBLogThreaded("calling  mach_exc_server");
278   state.task_port = task;
279   g_message = &state;
280   // The exc_server function is the MIG generated server handling function
281   // to handle messages from the kernel relating to the occurrence of an
282   // exception in a thread. Such messages are delivered to the exception port
283   // set via thread_set_exception_ports or task_set_exception_ports. When an
284   // exception occurs in a thread, the thread sends an exception message to
285   // its exception port, blocking in the kernel waiting for the receipt of a
286   // reply. The exc_server function performs all necessary argument handling
287   // for this kernel message and calls catch_exception_raise,
288   // catch_exception_raise_state or catch_exception_raise_state_identity,
289   // which should handle the exception. If the called routine returns
290   // KERN_SUCCESS, a reply message will be sent, allowing the thread to
291   // continue from the point of the exception; otherwise, no reply message
292   // is sent and the called routine must have dealt with the exception
293   // thread directly.
294   if (mach_exc_server(&exc_msg.hdr, &reply_msg.hdr)) {
295     success = true;
296   } else if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) {
297     DNBLogThreaded("mach_exc_server returned zero...");
298   }
299   g_message = NULL;
300   return success;
301 }
302 
303 kern_return_t MachException::Message::Reply(MachProcess *process, int signal) {
304   // Reply to the exception...
305   DNBError err;
306 
307   // If we had a soft signal, we need to update the thread first so it can
308   // continue without signaling
309   int soft_signal = state.SoftSignal();
310   if (soft_signal) {
311     int state_pid = -1;
312     if (process->Task().TaskPort() == state.task_port) {
313       // This is our task, so we can update the signal to send to it
314       state_pid = process->ProcessID();
315       soft_signal = signal;
316     } else {
317       err = ::pid_for_task(state.task_port, &state_pid);
318     }
319 
320     assert(state_pid != -1);
321     if (state_pid != -1) {
322       errno = 0;
323       if (::ptrace(PT_THUPDATE, state_pid,
324                    (caddr_t)((uintptr_t)state.thread_port), soft_signal) != 0)
325         err.SetError(errno, DNBError::POSIX);
326       else
327         err.Clear();
328 
329       if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
330         err.LogThreaded("::ptrace (request = PT_THUPDATE, pid = 0x%4.4x, tid = "
331                         "0x%4.4x, signal = %i)",
332                         state_pid, state.thread_port, soft_signal);
333     }
334   }
335 
336   DNBLogThreadedIf(
337       LOG_EXCEPTIONS, "::mach_msg ( msg->{bits = %#x, size = %u, remote_port = "
338                       "%#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, "
339                       "option = %#x, send_size = %u, rcv_size = %u, rcv_name = "
340                       "%#x, timeout = %u, notify = %#x)",
341       reply_msg.hdr.msgh_bits, reply_msg.hdr.msgh_size,
342       reply_msg.hdr.msgh_remote_port, reply_msg.hdr.msgh_local_port,
343       reply_msg.hdr.msgh_reserved, reply_msg.hdr.msgh_id,
344       MACH_SEND_MSG | MACH_SEND_INTERRUPT, reply_msg.hdr.msgh_size, 0,
345       MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
346 
347   err = ::mach_msg(&reply_msg.hdr, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
348                    reply_msg.hdr.msgh_size, 0, MACH_PORT_NULL,
349                    MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
350 
351   if (err.Fail()) {
352     if (err.Error() == MACH_SEND_INTERRUPTED) {
353       if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
354         err.LogThreaded("::mach_msg() - send interrupted");
355       // TODO: keep retrying to reply???
356     } else {
357       if (state.task_port == process->Task().TaskPort()) {
358         DNBLogThreaded("error: mach_msg() returned an error when replying to a "
359                        "mach exception: error = %u",
360                        err.Error());
361       } else {
362         if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
363           err.LogThreaded("::mach_msg() - failed (child of task)");
364       }
365     }
366   }
367 
368   return err.Error();
369 }
370 
371 void MachException::Data::Dump() const {
372   const char *exc_type_name = MachException::Name(exc_type);
373   DNBLogThreadedIf(
374       LOG_EXCEPTIONS, "    state { task_port = 0x%4.4x, thread_port =  "
375                       "0x%4.4x, exc_type = %i (%s) ...",
376       task_port, thread_port, exc_type, exc_type_name ? exc_type_name : "???");
377 
378   const size_t exc_data_count = exc_data.size();
379   // Dump any special exception data contents
380   int soft_signal = SoftSignal();
381   if (soft_signal != 0) {
382     const char *sig_str = SysSignal::Name(soft_signal);
383     DNBLogThreadedIf(LOG_EXCEPTIONS,
384                      "            exc_data: EXC_SOFT_SIGNAL (%i (%s))",
385                      soft_signal, sig_str ? sig_str : "unknown signal");
386   } else {
387     // No special disassembly for this data, just dump the data
388     size_t idx;
389     for (idx = 0; idx < exc_data_count; ++idx) {
390       DNBLogThreadedIf(LOG_EXCEPTIONS, "            exc_data[%llu]: 0x%llx",
391                        (uint64_t)idx, (uint64_t)exc_data[idx]);
392     }
393   }
394 }
395 
396 #define PREV_EXC_MASK_ALL                                                      \
397   (EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC |      \
398    EXC_MASK_EMULATION | EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT |              \
399    EXC_MASK_SYSCALL | EXC_MASK_MACH_SYSCALL | EXC_MASK_RPC_ALERT |             \
400    EXC_MASK_MACHINE)
401 
402 // Don't listen for EXC_RESOURCE, it should really get handled by the system
403 // handler.
404 
405 #ifndef EXC_RESOURCE
406 #define EXC_RESOURCE 11
407 #endif
408 
409 #ifndef EXC_MASK_RESOURCE
410 #define EXC_MASK_RESOURCE (1 << EXC_RESOURCE)
411 #endif
412 
413 #define LLDB_EXC_MASK (EXC_MASK_ALL & ~EXC_MASK_RESOURCE)
414 
415 kern_return_t MachException::PortInfo::Save(task_t task) {
416   DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE,
417                    "MachException::PortInfo::Save ( task = 0x%4.4x )", task);
418   // Be careful to be able to have debugserver built on a newer OS than what
419   // it is currently running on by being able to start with all exceptions
420   // and back off to just what is supported on the current system
421   DNBError err;
422 
423   mask = LLDB_EXC_MASK;
424 
425   count = (sizeof(ports) / sizeof(ports[0]));
426   err = ::task_get_exception_ports(task, mask, masks, &count, ports, behaviors,
427                                    flavors);
428   if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
429     err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = 0x%x, "
430                     "maskCnt => %u, ports, behaviors, flavors )",
431                     task, mask, count);
432 
433   if (err.Error() == KERN_INVALID_ARGUMENT && mask != PREV_EXC_MASK_ALL) {
434     mask = PREV_EXC_MASK_ALL;
435     count = (sizeof(ports) / sizeof(ports[0]));
436     err = ::task_get_exception_ports(task, mask, masks, &count, ports,
437                                      behaviors, flavors);
438     if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
439       err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = "
440                       "0x%x, maskCnt => %u, ports, behaviors, flavors )",
441                       task, mask, count);
442   }
443   if (err.Fail()) {
444     mask = 0;
445     count = 0;
446   }
447   return err.Error();
448 }
449 
450 kern_return_t MachException::PortInfo::Restore(task_t task) {
451   DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE,
452                    "MachException::PortInfo::Restore( task = 0x%4.4x )", task);
453   uint32_t i = 0;
454   DNBError err;
455   if (count > 0) {
456     for (i = 0; i < count; i++) {
457       err = ::task_set_exception_ports(task, masks[i], ports[i], behaviors[i],
458                                        flavors[i]);
459       if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
460         err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
461                         "exception_mask = 0x%8.8x, new_port = 0x%4.4x, "
462                         "behavior = 0x%8.8x, new_flavor = 0x%8.8x )",
463                         task, masks[i], ports[i], behaviors[i], flavors[i]);
464         // Bail if we encounter any errors
465       }
466 
467       if (err.Fail())
468         break;
469     }
470   }
471   count = 0;
472   return err.Error();
473 }
474 
475 const char *MachException::Name(exception_type_t exc_type) {
476   switch (exc_type) {
477   case EXC_BAD_ACCESS:
478     return "EXC_BAD_ACCESS";
479   case EXC_BAD_INSTRUCTION:
480     return "EXC_BAD_INSTRUCTION";
481   case EXC_ARITHMETIC:
482     return "EXC_ARITHMETIC";
483   case EXC_EMULATION:
484     return "EXC_EMULATION";
485   case EXC_SOFTWARE:
486     return "EXC_SOFTWARE";
487   case EXC_BREAKPOINT:
488     return "EXC_BREAKPOINT";
489   case EXC_SYSCALL:
490     return "EXC_SYSCALL";
491   case EXC_MACH_SYSCALL:
492     return "EXC_MACH_SYSCALL";
493   case EXC_RPC_ALERT:
494     return "EXC_RPC_ALERT";
495 #ifdef EXC_CRASH
496   case EXC_CRASH:
497     return "EXC_CRASH";
498 #endif
499   default:
500     break;
501   }
502   return NULL;
503 }
504