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