]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.cpp
Merge lldb trunk r366426, resolve conflicts, and update FREEBSD-Xlist.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / Process / Darwin / MachException.cpp
1 //===-- MachException.cpp ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  Created by Greg Clayton on 6/18/07.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "MachException.h"
14
15 // C includes
16 #include <errno.h>
17 #include <sys/ptrace.h>
18 #include <sys/types.h>
19
20 // C++ includes
21 #include <mutex>
22
23 // LLDB includes
24 #include "lldb/Target/UnixSignals.h"
25 #include "lldb/Utility/LLDBAssert.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/Status.h"
28 #include "lldb/Utility/Stream.h"
29
30 using namespace lldb;
31 using namespace lldb_private;
32 using namespace lldb_private::process_darwin;
33
34 // Routine mach_exception_raise
35 extern "C" kern_return_t
36 catch_mach_exception_raise(mach_port_t exception_port, mach_port_t thread,
37                            mach_port_t task, exception_type_t exception,
38                            mach_exception_data_t code,
39                            mach_msg_type_number_t codeCnt);
40
41 extern "C" kern_return_t catch_mach_exception_raise_state(
42     mach_port_t exception_port, exception_type_t exception,
43     const mach_exception_data_t code, mach_msg_type_number_t codeCnt,
44     int *flavor, const thread_state_t old_state,
45     mach_msg_type_number_t old_stateCnt, thread_state_t new_state,
46     mach_msg_type_number_t *new_stateCnt);
47
48 // Routine mach_exception_raise_state_identity
49 extern "C" kern_return_t catch_mach_exception_raise_state_identity(
50     mach_port_t exception_port, mach_port_t thread, mach_port_t task,
51     exception_type_t exception, mach_exception_data_t code,
52     mach_msg_type_number_t codeCnt, int *flavor, thread_state_t old_state,
53     mach_msg_type_number_t old_stateCnt, thread_state_t new_state,
54     mach_msg_type_number_t *new_stateCnt);
55
56 extern "C" boolean_t mach_exc_server(mach_msg_header_t *InHeadP,
57                                      mach_msg_header_t *OutHeadP);
58
59 static MachException::Data *g_message = NULL;
60
61 extern "C" kern_return_t catch_mach_exception_raise_state(
62     mach_port_t exc_port, exception_type_t exc_type,
63     const mach_exception_data_t exc_data, mach_msg_type_number_t exc_data_count,
64     int *flavor, const thread_state_t old_state,
65     mach_msg_type_number_t old_stateCnt, thread_state_t new_state,
66     mach_msg_type_number_t *new_stateCnt) {
67   // TODO change to LIBLLDB_LOG_EXCEPTION
68   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
69   if (log) {
70     log->Printf("::%s(exc_port = 0x%4.4x, exc_type = %d (%s), "
71                 "exc_data = 0x%llx, exc_data_count = %d)",
72                 __FUNCTION__, exc_port, exc_type, MachException::Name(exc_type),
73                 (uint64_t)exc_data, exc_data_count);
74   }
75   return KERN_FAILURE;
76 }
77
78 extern "C" kern_return_t catch_mach_exception_raise_state_identity(
79     mach_port_t exc_port, mach_port_t thread_port, mach_port_t task_port,
80     exception_type_t exc_type, mach_exception_data_t exc_data,
81     mach_msg_type_number_t exc_data_count, int *flavor,
82     thread_state_t old_state, mach_msg_type_number_t old_stateCnt,
83     thread_state_t new_state, mach_msg_type_number_t *new_stateCnt) {
84   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
85   if (log) {
86     log->Printf("::%s(exc_port = 0x%4.4x, thd_port = 0x%4.4x, "
87                 "tsk_port = 0x%4.4x, exc_type = %d (%s), exc_data[%d] = "
88                 "{ 0x%llx, 0x%llx })",
89                 __FUNCTION__, exc_port, thread_port, task_port, exc_type,
90                 MachException::Name(exc_type), exc_data_count,
91                 (uint64_t)(exc_data_count > 0 ? exc_data[0] : 0xBADDBADD),
92                 (uint64_t)(exc_data_count > 1 ? exc_data[1] : 0xBADDBADD));
93   }
94
95   return KERN_FAILURE;
96 }
97
98 extern "C" kern_return_t
99 catch_mach_exception_raise(mach_port_t exc_port, mach_port_t thread_port,
100                            mach_port_t task_port, exception_type_t exc_type,
101                            mach_exception_data_t exc_data,
102                            mach_msg_type_number_t exc_data_count) {
103   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
104   if (log) {
105     log->Printf("::%s(exc_port = 0x%4.4x, thd_port = 0x%4.4x, "
106                 "tsk_port = 0x%4.4x, exc_type = %d (%s), exc_data[%d] "
107                 "= { 0x%llx, 0x%llx })",
108                 __FUNCTION__, exc_port, thread_port, task_port, exc_type,
109                 MachException::Name(exc_type), exc_data_count,
110                 (uint64_t)(exc_data_count > 0 ? exc_data[0] : 0xBADDBADD),
111                 (uint64_t)(exc_data_count > 1 ? exc_data[1] : 0xBADDBADD));
112   }
113
114   if (task_port == g_message->task_port) {
115     g_message->task_port = task_port;
116     g_message->thread_port = thread_port;
117     g_message->exc_type = exc_type;
118     g_message->exc_data.resize(exc_data_count);
119     ::memcpy(&g_message->exc_data[0], exc_data,
120              g_message->exc_data.size() * sizeof(mach_exception_data_type_t));
121     return KERN_SUCCESS;
122   }
123   return KERN_FAILURE;
124 }
125
126 bool MachException::Data::GetStopInfo(struct ThreadStopInfo *stop_info,
127                                       const UnixSignals &signals,
128                                       Stream &stream) const {
129   if (!stop_info)
130     return false;
131
132   // Zero out the structure.
133   memset(stop_info, 0, sizeof(struct ThreadStopInfo));
134
135   if (exc_type == 0) {
136     stop_info->reason = eStopReasonInvalid;
137     return true;
138   }
139
140   // We always stop with a mach exception.
141   stop_info->reason = eStopReasonException;
142   // Save the EXC_XXXX exception type.
143   stop_info->details.exception.type = exc_type;
144
145   // Fill in a text description
146   const char *exc_name = MachException::Name(exc_type);
147   if (exc_name)
148     stream.Printf("%s", exc_name);
149   else
150     stream.Printf("%i", exc_type);
151
152   stop_info->details.exception.data_count = exc_data.size();
153
154   int soft_signal = SoftSignal();
155   if (soft_signal) {
156     const char *sig_str = signals.GetSignalAsCString(soft_signal);
157     stream.Printf(" EXC_SOFT_SIGNAL( %i ( %s ))", soft_signal,
158                   sig_str ? sig_str : "unknown signal");
159   } else {
160     // No special disassembly for exception data, just print it.
161     size_t idx;
162     stream.Printf(" data[%llu] = {",
163                   (uint64_t)stop_info->details.exception.data_count);
164
165     for (idx = 0; idx < stop_info->details.exception.data_count; ++idx) {
166       stream.Printf(
167           "0x%llx%c", (uint64_t)exc_data[idx],
168           ((idx + 1 == stop_info->details.exception.data_count) ? '}' : ','));
169     }
170   }
171
172   // Copy the exception data
173   for (size_t i = 0; i < stop_info->details.exception.data_count; i++)
174     stop_info->details.exception.data[i] = exc_data[i];
175
176   return true;
177 }
178
179 Status MachException::Message::Receive(mach_port_t port,
180                                        mach_msg_option_t options,
181                                        mach_msg_timeout_t timeout,
182                                        mach_port_t notify_port) {
183   Status error;
184   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
185
186   mach_msg_timeout_t mach_msg_timeout =
187       options & MACH_RCV_TIMEOUT ? timeout : 0;
188   if (log && ((options & MACH_RCV_TIMEOUT) == 0)) {
189     // Dump this log message if we have no timeout in case it never returns
190     log->Printf("::mach_msg(msg->{bits = %#x, size = %u remote_port = %#x, "
191                 "local_port = %#x, reserved = 0x%x, id = 0x%x}, "
192                 "option = %#x, send_size = 0, rcv_size = %llu, "
193                 "rcv_name = %#x, timeout = %u, notify = %#x)",
194                 exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
195                 exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
196                 exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id, options,
197                 (uint64_t)sizeof(exc_msg.data), port, mach_msg_timeout,
198                 notify_port);
199   }
200
201   mach_msg_return_t mach_err =
202       ::mach_msg(&exc_msg.hdr,
203                  options,              // options
204                  0,                    // Send size
205                  sizeof(exc_msg.data), // Receive size
206                  port,                 // exception port to watch for
207                                        // exception on
208                  mach_msg_timeout,     // timeout in msec (obeyed only
209                                        // if MACH_RCV_TIMEOUT is ORed
210                                        // into the options parameter)
211                  notify_port);
212   error.SetError(mach_err, eErrorTypeMachKernel);
213
214   // Dump any errors we get
215   if (error.Fail() && log) {
216     log->Printf("::mach_msg(msg->{bits = %#x, size = %u remote_port = %#x, "
217                 "local_port = %#x, reserved = 0x%x, id = 0x%x}, "
218                 "option = %#x, send_size = %u, rcv_size = %lu, rcv_name "
219                 "= %#x, timeout = %u, notify = %#x) failed: %s",
220                 exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
221                 exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
222                 exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id, options, 0,
223                 sizeof(exc_msg.data), port, mach_msg_timeout, notify_port,
224                 error.AsCString());
225   }
226   return error;
227 }
228
229 void MachException::Message::Dump(Stream &stream) const {
230   stream.Printf("  exc_msg { bits = 0x%8.8x size = 0x%8.8x remote-port = "
231                 "0x%8.8x local-port = 0x%8.8x reserved = 0x%8.8x id = "
232                 "0x%8.8x }\n",
233                 exc_msg.hdr.msgh_bits, exc_msg.hdr.msgh_size,
234                 exc_msg.hdr.msgh_remote_port, exc_msg.hdr.msgh_local_port,
235                 exc_msg.hdr.msgh_reserved, exc_msg.hdr.msgh_id);
236
237   stream.Printf("  reply_msg { bits = 0x%8.8x size = 0x%8.8x remote-port = "
238                 "0x%8.8x local-port = 0x%8.8x reserved = 0x%8.8x id = "
239                 "0x%8.8x }",
240                 reply_msg.hdr.msgh_bits, reply_msg.hdr.msgh_size,
241                 reply_msg.hdr.msgh_remote_port, reply_msg.hdr.msgh_local_port,
242                 reply_msg.hdr.msgh_reserved, reply_msg.hdr.msgh_id);
243 }
244
245 bool MachException::Message::CatchExceptionRaise(task_t task) {
246   bool success = false;
247   state.task_port = task;
248   g_message = &state;
249   // The exc_server function is the MIG generated server handling function to
250   // handle messages from the kernel relating to the occurrence of an exception
251   // in a thread. Such messages are delivered to the exception port set via
252   // thread_set_exception_ports or task_set_exception_ports. When an exception
253   // occurs in a thread, the thread sends an exception message to its exception
254   // port, blocking in the kernel waiting for the receipt of a reply. The
255   // exc_server function performs all necessary argument handling for this
256   // kernel message and calls catch_exception_raise,
257   // catch_exception_raise_state or catch_exception_raise_state_identity, which
258   // should handle the exception. If the called routine returns KERN_SUCCESS, a
259   // reply message will be sent, allowing the thread to continue from the point
260   // of the exception; otherwise, no reply message is sent and the called
261   // routine must have dealt with the exception thread directly.
262   if (mach_exc_server(&exc_msg.hdr, &reply_msg.hdr)) {
263     success = true;
264   } else {
265     Log *log(
266         GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
267     if (log)
268       log->Printf("MachException::Message::%s(): mach_exc_server "
269                   "returned zero...",
270                   __FUNCTION__);
271   }
272   g_message = NULL;
273   return success;
274 }
275
276 Status MachException::Message::Reply(::pid_t inferior_pid, task_t inferior_task,
277                                      int signal) {
278   // Reply to the exception...
279   Status error;
280
281   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
282
283   // If we had a soft signal, we need to update the thread first so it can
284   // continue without signaling
285   int soft_signal = state.SoftSignal();
286   if (soft_signal) {
287     int state_pid = -1;
288     if (inferior_task == state.task_port) {
289       // This is our task, so we can update the signal to send to it
290       state_pid = inferior_pid;
291       soft_signal = signal;
292     } else {
293       auto mach_err = ::pid_for_task(state.task_port, &state_pid);
294       if (mach_err) {
295         error.SetError(mach_err, eErrorTypeMachKernel);
296         if (log)
297           log->Printf("MachException::Message::%s(): pid_for_task() "
298                       "failed: %s",
299                       __FUNCTION__, error.AsCString());
300         return error;
301       }
302     }
303
304     lldbassert(state_pid != -1);
305     if (state_pid != -1) {
306       errno = 0;
307       caddr_t thread_port_caddr = (caddr_t)(uintptr_t)state.thread_port;
308       if (::ptrace(PT_THUPDATE, state_pid, thread_port_caddr, soft_signal) != 0)
309         error.SetError(errno, eErrorTypePOSIX);
310
311       if (!error.Success()) {
312         if (log)
313           log->Printf("::ptrace(request = PT_THUPDATE, pid = "
314                       "0x%4.4x, tid = 0x%4.4x, signal = %i)",
315                       state_pid, state.thread_port, soft_signal);
316         return error;
317       }
318     }
319   }
320
321   if (log)
322     log->Printf("::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   auto mach_err =
333       ::mach_msg(&reply_msg.hdr, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
334                  reply_msg.hdr.msgh_size, 0, MACH_PORT_NULL,
335                  MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
336   if (mach_err)
337     error.SetError(mach_err, eErrorTypeMachKernel);
338
339   // Log our error if we have one.
340   if (error.Fail() && log) {
341     if (error.GetError() == MACH_SEND_INTERRUPTED) {
342       log->PutCString("::mach_msg() - send interrupted");
343       // TODO: keep retrying to reply???
344     } else if (state.task_port == inferior_task) {
345       log->Printf("mach_msg(): returned an error when replying "
346                   "to a mach exception: error = %u (%s)",
347                   error.GetError(), error.AsCString());
348     } else {
349       log->Printf("::mach_msg() - failed (child of task): %u (%s)",
350                   error.GetError(), error.AsCString());
351     }
352   }
353
354   return error;
355 }
356
357 #define PREV_EXC_MASK_ALL                                                      \
358   (EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC |      \
359    EXC_MASK_EMULATION | EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT |              \
360    EXC_MASK_SYSCALL | EXC_MASK_MACH_SYSCALL | EXC_MASK_RPC_ALERT |             \
361    EXC_MASK_MACHINE)
362
363 // Don't listen for EXC_RESOURCE, it should really get handled by the system
364 // handler.
365
366 #ifndef EXC_RESOURCE
367 #define EXC_RESOURCE 11
368 #endif
369
370 #ifndef EXC_MASK_RESOURCE
371 #define EXC_MASK_RESOURCE (1 << EXC_RESOURCE)
372 #endif
373
374 #define LLDB_EXC_MASK (EXC_MASK_ALL & ~EXC_MASK_RESOURCE)
375
376 Status MachException::PortInfo::Save(task_t task) {
377   Status error;
378   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
379
380   if (log)
381     log->Printf("MachException::PortInfo::%s(task = 0x%4.4x)", __FUNCTION__,
382                 task);
383
384   // Be careful to be able to have debugserver built on a newer OS than what it
385   // is currently running on by being able to start with all exceptions and
386   // back off to just what is supported on the current system
387   mask = LLDB_EXC_MASK;
388
389   count = (sizeof(ports) / sizeof(ports[0]));
390   auto mach_err = ::task_get_exception_ports(task, mask, masks, &count, ports,
391                                              behaviors, flavors);
392   if (mach_err)
393     error.SetError(mach_err, eErrorTypeMachKernel);
394
395   if (log) {
396     if (error.Success()) {
397       log->Printf("::task_get_exception_ports(task = 0x%4.4x, mask = "
398                   "0x%x, maskCnt => %u, ports, behaviors, flavors)",
399                   task, mask, count);
400     } else {
401       log->Printf("::task_get_exception_ports(task = 0x%4.4x, mask = 0x%x, "
402                   "maskCnt => %u, ports, behaviors, flavors) error: %u (%s)",
403                   task, mask, count, error.GetError(), error.AsCString());
404     }
405   }
406
407   if ((error.GetError() == KERN_INVALID_ARGUMENT) &&
408       (mask != PREV_EXC_MASK_ALL)) {
409     mask = PREV_EXC_MASK_ALL;
410     count = (sizeof(ports) / sizeof(ports[0]));
411     mach_err = ::task_get_exception_ports(task, mask, masks, &count, ports,
412                                           behaviors, flavors);
413     error.SetError(mach_err, eErrorTypeMachKernel);
414     if (log) {
415       if (error.Success()) {
416         log->Printf("::task_get_exception_ports(task = 0x%4.4x, "
417                     "mask = 0x%x, maskCnt => %u, ports, behaviors, "
418                     "flavors)",
419                     task, mask, count);
420       } else {
421         log->Printf("::task_get_exception_ports(task = 0x%4.4x, mask = "
422                     "0x%x, maskCnt => %u, ports, behaviors, flavors) "
423                     "error: %u (%s)",
424                     task, mask, count, error.GetError(), error.AsCString());
425       }
426     }
427   }
428   if (error.Fail()) {
429     mask = 0;
430     count = 0;
431   }
432   return error;
433 }
434
435 Status MachException::PortInfo::Restore(task_t task) {
436   Status error;
437
438   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
439
440   if (log)
441     log->Printf("MachException::PortInfo::Restore(task = 0x%4.4x)", task);
442
443   uint32_t i = 0;
444   if (count > 0) {
445     for (i = 0; i < count; i++) {
446       auto mach_err = ::task_set_exception_ports(task, masks[i], ports[i],
447                                                  behaviors[i], flavors[i]);
448       if (mach_err)
449         error.SetError(mach_err, eErrorTypeMachKernel);
450       if (log) {
451         if (error.Success()) {
452           log->Printf("::task_set_exception_ports(task = 0x%4.4x, "
453                       "exception_mask = 0x%8.8x, new_port = 0x%4.4x, "
454                       "behavior = 0x%8.8x, new_flavor = 0x%8.8x)",
455                       task, masks[i], ports[i], behaviors[i], flavors[i]);
456         } else {
457           log->Printf("::task_set_exception_ports(task = 0x%4.4x, "
458                       "exception_mask = 0x%8.8x, new_port = 0x%4.4x, "
459                       "behavior = 0x%8.8x, new_flavor = 0x%8.8x): "
460                       "error %u (%s)",
461                       task, masks[i], ports[i], behaviors[i], flavors[i],
462                       error.GetError(), error.AsCString());
463         }
464       }
465
466       // Bail if we encounter any errors
467       if (error.Fail())
468         break;
469     }
470   }
471
472   count = 0;
473   return error;
474 }
475
476 const char *MachException::Name(exception_type_t exc_type) {
477   switch (exc_type) {
478   case EXC_BAD_ACCESS:
479     return "EXC_BAD_ACCESS";
480   case EXC_BAD_INSTRUCTION:
481     return "EXC_BAD_INSTRUCTION";
482   case EXC_ARITHMETIC:
483     return "EXC_ARITHMETIC";
484   case EXC_EMULATION:
485     return "EXC_EMULATION";
486   case EXC_SOFTWARE:
487     return "EXC_SOFTWARE";
488   case EXC_BREAKPOINT:
489     return "EXC_BREAKPOINT";
490   case EXC_SYSCALL:
491     return "EXC_SYSCALL";
492   case EXC_MACH_SYSCALL:
493     return "EXC_MACH_SYSCALL";
494   case EXC_RPC_ALERT:
495     return "EXC_RPC_ALERT";
496 #ifdef EXC_CRASH
497   case EXC_CRASH:
498     return "EXC_CRASH";
499 #endif
500   default:
501     break;
502   }
503   return NULL;
504 }