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