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