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 
110   if (task_port == g_message->task_port) {
111     g_message->task_port = task_port;
112     g_message->thread_port = thread_port;
113     g_message->exc_type = exc_type;
114     g_message->exc_data.resize(exc_data_count);
115     ::memcpy(&g_message->exc_data[0], exc_data,
116              g_message->exc_data.size() * sizeof(mach_exception_data_type_t));
117     return KERN_SUCCESS;
118   }
119   return KERN_FAILURE;
120 }
121 
122 void MachException::Message::Dump() const {
123   DNBLogThreadedIf(LOG_EXCEPTIONS, "  exc_msg { bits = 0x%8.8x size = 0x%8.8x "
124                                    "remote-port = 0x%8.8x local-port = 0x%8.8x "
125                                    "reserved = 0x%8.8x id = 0x%8.8x } ",
126                    exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
127                    exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
128                    exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id);
129 
130   DNBLogThreadedIf(LOG_EXCEPTIONS, "reply_msg { bits = 0x%8.8x size = 0x%8.8x "
131                                    "remote-port = 0x%8.8x local-port = 0x%8.8x "
132                                    "reserved = 0x%8.8x id = 0x%8.8x }",
133                    reply_msg.hdr.msgh_bits, reply_msg.hdr.msgh_size,
134                    reply_msg.hdr.msgh_remote_port,
135                    reply_msg.hdr.msgh_local_port, reply_msg.hdr.msgh_reserved,
136                    reply_msg.hdr.msgh_id);
137 
138   state.Dump();
139 }
140 
141 bool MachException::Data::GetStopInfo(
142     struct DNBThreadStopInfo *stop_info) const {
143   // Zero out the structure.
144   memset(stop_info, 0, sizeof(struct DNBThreadStopInfo));
145 
146   if (exc_type == 0) {
147     stop_info->reason = eStopTypeInvalid;
148     return true;
149   }
150 
151   // We always stop with a mach exceptions
152   stop_info->reason = eStopTypeException;
153   // Save the EXC_XXXX exception type
154   stop_info->details.exception.type = exc_type;
155 
156   // Fill in a text description
157   const char *exc_name = MachException::Name(exc_type);
158   char *desc = stop_info->description;
159   const char *end_desc = desc + DNB_THREAD_STOP_INFO_MAX_DESC_LENGTH;
160   if (exc_name)
161     desc +=
162         snprintf(desc, DNB_THREAD_STOP_INFO_MAX_DESC_LENGTH, "%s", exc_name);
163   else
164     desc +=
165         snprintf(desc, DNB_THREAD_STOP_INFO_MAX_DESC_LENGTH, "%i", exc_type);
166 
167   stop_info->details.exception.data_count = exc_data.size();
168 
169   int soft_signal = SoftSignal();
170   if (soft_signal) {
171     if (desc < end_desc) {
172       const char *sig_str = SysSignal::Name(soft_signal);
173       snprintf(desc, end_desc - desc, " EXC_SOFT_SIGNAL( %i ( %s ))",
174                soft_signal, sig_str ? sig_str : "unknown signal");
175     }
176   } else {
177     // No special disassembly for exception data, just
178     size_t idx;
179     if (desc < end_desc) {
180       desc += snprintf(desc, end_desc - desc, " data[%llu] = {",
181                        (uint64_t)stop_info->details.exception.data_count);
182 
183       for (idx = 0;
184            desc < end_desc && idx < stop_info->details.exception.data_count;
185            ++idx)
186         desc += snprintf(
187             desc, end_desc - desc, "0x%llx%c", (uint64_t)exc_data[idx],
188             ((idx + 1 == stop_info->details.exception.data_count) ? '}' : ','));
189     }
190   }
191 
192   // Copy the exception data
193   size_t i;
194   for (i = 0; i < stop_info->details.exception.data_count; i++)
195     stop_info->details.exception.data[i] = exc_data[i];
196 
197   return true;
198 }
199 
200 void MachException::Data::DumpStopReason() const {
201   int soft_signal = SoftSignal();
202   if (soft_signal) {
203     const char *signal_str = SysSignal::Name(soft_signal);
204     if (signal_str)
205       DNBLog("signal(%s)", signal_str);
206     else
207       DNBLog("signal(%i)", soft_signal);
208     return;
209   }
210   DNBLog("%s", Name(exc_type));
211 }
212 
213 kern_return_t MachException::Message::Receive(mach_port_t port,
214                                               mach_msg_option_t options,
215                                               mach_msg_timeout_t timeout,
216                                               mach_port_t notify_port) {
217   DNBError err;
218   const bool log_exceptions = DNBLogCheckLogBit(LOG_EXCEPTIONS);
219   mach_msg_timeout_t mach_msg_timeout =
220       options & MACH_RCV_TIMEOUT ? timeout : 0;
221   if (log_exceptions && ((options & MACH_RCV_TIMEOUT) == 0)) {
222     // Dump this log message if we have no timeout in case it never returns
223     DNBLogThreaded("::mach_msg ( msg->{bits = %#x, size = %u remote_port = "
224                    "%#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, option "
225                    "= %#x, send_size = 0, rcv_size = %llu, rcv_name = %#x, "
226                    "timeout = %u, notify = %#x)",
227                    exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
228                    exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
229                    exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id, options,
230                    (uint64_t)sizeof(exc_msg.data), port, mach_msg_timeout,
231                    notify_port);
232   }
233 
234   err = ::mach_msg(&exc_msg.hdr,
235                    options,              // options
236                    0,                    // Send size
237                    sizeof(exc_msg.data), // Receive size
238                    port,             // exception port to watch for exception on
239                    mach_msg_timeout, // timeout in msec (obeyed only if
240                                      // MACH_RCV_TIMEOUT is ORed into the
241                                      // options parameter)
242                    notify_port);
243 
244   // Dump any errors we get
245   if (log_exceptions) {
246     err.LogThreaded("::mach_msg ( msg->{bits = %#x, size = %u remote_port = "
247                     "%#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, "
248                     "option = %#x, send_size = %u, rcv_size = %u, rcv_name = "
249                     "%#x, timeout = %u, notify = %#x)",
250                     exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
251                     exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
252                     exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id, options, 0,
253                     sizeof(exc_msg.data), port, mach_msg_timeout, notify_port);
254   }
255   return err.Error();
256 }
257 
258 bool MachException::Message::CatchExceptionRaise(task_t task) {
259   bool success = false;
260   // locker will keep a mutex locked until it goes out of scope
261   //    PThreadMutex::Locker locker(&g_message_mutex);
262   //    DNBLogThreaded("calling  mach_exc_server");
263   state.task_port = task;
264   g_message = &state;
265   // The exc_server function is the MIG generated server handling function
266   // to handle messages from the kernel relating to the occurrence of an
267   // exception in a thread. Such messages are delivered to the exception port
268   // set via thread_set_exception_ports or task_set_exception_ports. When an
269   // exception occurs in a thread, the thread sends an exception message to
270   // its exception port, blocking in the kernel waiting for the receipt of a
271   // reply. The exc_server function performs all necessary argument handling
272   // for this kernel message and calls catch_exception_raise,
273   // catch_exception_raise_state or catch_exception_raise_state_identity,
274   // which should handle the exception. If the called routine returns
275   // KERN_SUCCESS, a reply message will be sent, allowing the thread to
276   // continue from the point of the exception; otherwise, no reply message
277   // is sent and the called routine must have dealt with the exception
278   // thread directly.
279   if (mach_exc_server(&exc_msg.hdr, &reply_msg.hdr)) {
280     success = true;
281   } else if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) {
282     DNBLogThreaded("mach_exc_server returned zero...");
283   }
284   g_message = NULL;
285   return success;
286 }
287 
288 kern_return_t MachException::Message::Reply(MachProcess *process, int signal) {
289   // Reply to the exception...
290   DNBError err;
291 
292   // If we had a soft signal, we need to update the thread first so it can
293   // continue without signaling
294   int soft_signal = state.SoftSignal();
295   if (soft_signal) {
296     int state_pid = -1;
297     if (process->Task().TaskPort() == state.task_port) {
298       // This is our task, so we can update the signal to send to it
299       state_pid = process->ProcessID();
300       soft_signal = signal;
301     } else {
302       err = ::pid_for_task(state.task_port, &state_pid);
303     }
304 
305     assert(state_pid != -1);
306     if (state_pid != -1) {
307       errno = 0;
308       if (::ptrace(PT_THUPDATE, state_pid,
309                    (caddr_t)((uintptr_t)state.thread_port), soft_signal) != 0)
310         err.SetError(errno, DNBError::POSIX);
311       else
312         err.Clear();
313 
314       if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
315         err.LogThreaded("::ptrace (request = PT_THUPDATE, pid = 0x%4.4x, tid = "
316                         "0x%4.4x, signal = %i)",
317                         state_pid, state.thread_port, soft_signal);
318     }
319   }
320 
321   DNBLogThreadedIf(
322       LOG_EXCEPTIONS, "::mach_msg ( msg->{bits = %#x, size = %u, remote_port = "
323                       "%#x, local_port = %#x, reserved = 0x%x, id = 0x%x}, "
324                       "option = %#x, send_size = %u, rcv_size = %u, rcv_name = "
325                       "%#x, timeout = %u, notify = %#x)",
326       reply_msg.hdr.msgh_bits, reply_msg.hdr.msgh_size,
327       reply_msg.hdr.msgh_remote_port, reply_msg.hdr.msgh_local_port,
328       reply_msg.hdr.msgh_reserved, reply_msg.hdr.msgh_id,
329       MACH_SEND_MSG | MACH_SEND_INTERRUPT, reply_msg.hdr.msgh_size, 0,
330       MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
331 
332   err = ::mach_msg(&reply_msg.hdr, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
333                    reply_msg.hdr.msgh_size, 0, MACH_PORT_NULL,
334                    MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
335 
336   if (err.Fail()) {
337     if (err.Error() == MACH_SEND_INTERRUPTED) {
338       if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
339         err.LogThreaded("::mach_msg() - send interrupted");
340       // TODO: keep retrying to reply???
341     } else {
342       if (state.task_port == process->Task().TaskPort()) {
343         DNBLogThreaded("error: mach_msg() returned an error when replying to a "
344                        "mach exception: error = %u",
345                        err.Error());
346       } else {
347         if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
348           err.LogThreaded("::mach_msg() - failed (child of task)");
349       }
350     }
351   }
352 
353   return err.Error();
354 }
355 
356 void MachException::Data::Dump() const {
357   const char *exc_type_name = MachException::Name(exc_type);
358   DNBLogThreadedIf(
359       LOG_EXCEPTIONS, "    state { task_port = 0x%4.4x, thread_port =  "
360                       "0x%4.4x, exc_type = %i (%s) ...",
361       task_port, thread_port, exc_type, exc_type_name ? exc_type_name : "???");
362 
363   const size_t exc_data_count = exc_data.size();
364   // Dump any special exception data contents
365   int soft_signal = SoftSignal();
366   if (soft_signal != 0) {
367     const char *sig_str = SysSignal::Name(soft_signal);
368     DNBLogThreadedIf(LOG_EXCEPTIONS,
369                      "            exc_data: EXC_SOFT_SIGNAL (%i (%s))",
370                      soft_signal, sig_str ? sig_str : "unknown signal");
371   } else {
372     // No special disassembly for this data, just dump the data
373     size_t idx;
374     for (idx = 0; idx < exc_data_count; ++idx) {
375       DNBLogThreadedIf(LOG_EXCEPTIONS, "            exc_data[%llu]: 0x%llx",
376                        (uint64_t)idx, (uint64_t)exc_data[idx]);
377     }
378   }
379 }
380 
381 #define PREV_EXC_MASK_ALL                                                      \
382   (EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC |      \
383    EXC_MASK_EMULATION | EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT |              \
384    EXC_MASK_SYSCALL | EXC_MASK_MACH_SYSCALL | EXC_MASK_RPC_ALERT |             \
385    EXC_MASK_MACHINE)
386 
387 // Don't listen for EXC_RESOURCE, it should really get handled by the system
388 // handler.
389 
390 #ifndef EXC_RESOURCE
391 #define EXC_RESOURCE 11
392 #endif
393 
394 #ifndef EXC_MASK_RESOURCE
395 #define EXC_MASK_RESOURCE (1 << EXC_RESOURCE)
396 #endif
397 
398 #define LLDB_EXC_MASK (EXC_MASK_ALL & ~EXC_MASK_RESOURCE)
399 
400 kern_return_t MachException::PortInfo::Save(task_t task) {
401   DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE,
402                    "MachException::PortInfo::Save ( task = 0x%4.4x )", task);
403   // Be careful to be able to have debugserver built on a newer OS than what
404   // it is currently running on by being able to start with all exceptions
405   // and back off to just what is supported on the current system
406   DNBError err;
407 
408   mask = LLDB_EXC_MASK;
409 
410   count = (sizeof(ports) / sizeof(ports[0]));
411   err = ::task_get_exception_ports(task, mask, masks, &count, ports, behaviors,
412                                    flavors);
413   if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
414     err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = 0x%x, "
415                     "maskCnt => %u, ports, behaviors, flavors )",
416                     task, mask, count);
417 
418   if (err.Error() == KERN_INVALID_ARGUMENT && mask != PREV_EXC_MASK_ALL) {
419     mask = PREV_EXC_MASK_ALL;
420     count = (sizeof(ports) / sizeof(ports[0]));
421     err = ::task_get_exception_ports(task, mask, masks, &count, ports,
422                                      behaviors, flavors);
423     if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
424       err.LogThreaded("::task_get_exception_ports ( task = 0x%4.4x, mask = "
425                       "0x%x, maskCnt => %u, ports, behaviors, flavors )",
426                       task, mask, count);
427   }
428   if (err.Fail()) {
429     mask = 0;
430     count = 0;
431   }
432   return err.Error();
433 }
434 
435 kern_return_t MachException::PortInfo::Restore(task_t task) {
436   DNBLogThreadedIf(LOG_EXCEPTIONS | LOG_VERBOSE,
437                    "MachException::PortInfo::Restore( task = 0x%4.4x )", task);
438   uint32_t i = 0;
439   DNBError err;
440   if (count > 0) {
441     for (i = 0; i < count; i++) {
442       err = ::task_set_exception_ports(task, masks[i], ports[i], behaviors[i],
443                                        flavors[i]);
444       if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
445         err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
446                         "exception_mask = 0x%8.8x, new_port = 0x%4.4x, "
447                         "behavior = 0x%8.8x, new_flavor = 0x%8.8x )",
448                         task, masks[i], ports[i], behaviors[i], flavors[i]);
449         // Bail if we encounter any errors
450       }
451 
452       if (err.Fail())
453         break;
454     }
455   }
456   count = 0;
457   return err.Error();
458 }
459 
460 const char *MachException::Name(exception_type_t exc_type) {
461   switch (exc_type) {
462   case EXC_BAD_ACCESS:
463     return "EXC_BAD_ACCESS";
464   case EXC_BAD_INSTRUCTION:
465     return "EXC_BAD_INSTRUCTION";
466   case EXC_ARITHMETIC:
467     return "EXC_ARITHMETIC";
468   case EXC_EMULATION:
469     return "EXC_EMULATION";
470   case EXC_SOFTWARE:
471     return "EXC_SOFTWARE";
472   case EXC_BREAKPOINT:
473     return "EXC_BREAKPOINT";
474   case EXC_SYSCALL:
475     return "EXC_SYSCALL";
476   case EXC_MACH_SYSCALL:
477     return "EXC_MACH_SYSCALL";
478   case EXC_RPC_ALERT:
479     return "EXC_RPC_ALERT";
480 #ifdef EXC_CRASH
481   case EXC_CRASH:
482     return "EXC_CRASH";
483 #endif
484   default:
485     break;
486   }
487   return NULL;
488 }
489