testsuite: skip confirmation in 'gdb_reinitialize_dir'
[binutils-gdb.git] / gdb / darwin-nat.c
blobe4243f676487cc84d2e6fd1527482a8e899dba46
1 /* Darwin support for GDB, the GNU debugger.
2 Copyright (C) 2008-2024 Free Software Foundation, Inc.
4 Contributed by AdaCore.
6 This file is part of GDB.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "extract-store-integer.h"
22 #include "top.h"
23 #include "inferior.h"
24 #include "target.h"
25 #include "symfile.h"
26 #include "symtab.h"
27 #include "objfiles.h"
28 #include "cli/cli-cmds.h"
29 #include "gdbcore.h"
30 #include "gdbthread.h"
31 #include "regcache.h"
32 #include "event-top.h"
33 #include "inf-loop.h"
34 #include <sys/stat.h>
35 #include "inf-child.h"
36 #include "value.h"
37 #include "arch-utils.h"
38 #include "bfd.h"
39 #include "bfd/mach-o.h"
40 #include "gdbarch.h"
42 #include <copyfile.h>
43 #include <sys/ptrace.h>
44 #include <sys/signal.h>
45 #include <setjmp.h>
46 #include <sys/types.h>
47 #include <unistd.h>
48 #include <signal.h>
49 #include <ctype.h>
50 #include <sys/sysctl.h>
51 #include <sys/proc.h>
52 #include <libproc.h>
53 #include <sys/syscall.h>
54 #include <spawn.h>
56 #include <mach/mach_error.h>
57 #include <mach/mach_vm.h>
58 #include <mach/mach_init.h>
59 #include <mach/vm_map.h>
60 #include <mach/task.h>
61 #include <mach/mach_port.h>
62 #include <mach/thread_act.h>
63 #include <mach/port.h>
65 #include "darwin-nat.h"
66 #include "filenames.h"
67 #include "gdbsupport/filestuff.h"
68 #include "gdbsupport/gdb_unlinker.h"
69 #include "gdbsupport/pathstuff.h"
70 #include "gdbsupport/scoped_fd.h"
71 #include "gdbsupport/scoped_restore.h"
72 #include "nat/fork-inferior.h"
74 /* Quick overview.
75 Darwin kernel is Mach + BSD derived kernel. Note that they share the
76 same memory space and are linked together (ie there is no micro-kernel).
78 Although ptrace(2) is available on Darwin, it is not complete. We have
79 to use Mach calls to read and write memory and to modify registers. We
80 also use Mach to get inferior faults. As we cannot use select(2) or
81 signals with Mach port (the Mach communication channel), signals are
82 reported to gdb as an exception. Furthermore we detect death of the
83 inferior through a Mach notification message. This way we only wait
84 on Mach ports.
86 Some Mach documentation is available for Apple xnu source package or
87 from the web. */
90 #define PTRACE(CMD, PID, ADDR, SIG) \
91 darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
93 static void darwin_ptrace_me (void);
95 static void darwin_encode_reply (mig_reply_error_t *reply,
96 mach_msg_header_t *hdr, integer_t code);
98 static void darwin_setup_request_notification (struct inferior *inf);
99 static void darwin_deallocate_exception_ports (darwin_inferior *inf);
100 static void darwin_setup_exceptions (struct inferior *inf);
101 static void darwin_deallocate_threads (struct inferior *inf);
103 /* Task identifier of gdb. */
104 static task_t gdb_task;
106 /* A copy of mach_host_self (). */
107 mach_port_t darwin_host_self;
109 /* Exception port. */
110 mach_port_t darwin_ex_port;
112 /* Port set, to wait for answer on all ports. */
113 mach_port_t darwin_port_set;
115 /* Page size. */
116 static vm_size_t mach_page_size;
118 /* If Set, catch all mach exceptions (before they are converted to signals
119 by the kernel). */
120 static bool enable_mach_exceptions;
122 /* Inferior that should report a fake stop event. */
123 static struct inferior *darwin_inf_fake_stop;
125 /* If non-NULL, the shell we actually invoke. See maybe_cache_shell
126 for details. */
127 static const char *copied_shell;
129 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
130 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
132 /* This controls output of inferior debugging. */
133 static unsigned int darwin_debug_flag = 0;
135 /* Create a __TEXT __info_plist section in the executable so that gdb could
136 be signed. This is required to get an authorization for task_for_pid.
138 Once gdb is built, you must codesign it with any system-trusted signing
139 authority. See taskgated(8) for details. */
140 static const unsigned char info_plist[]
141 __attribute__ ((section ("__TEXT,__info_plist"),used)) =
142 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
143 "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
144 " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
145 "<plist version=\"1.0\">\n"
146 "<dict>\n"
147 " <key>CFBundleIdentifier</key>\n"
148 " <string>org.gnu.gdb</string>\n"
149 " <key>CFBundleName</key>\n"
150 " <string>gdb</string>\n"
151 " <key>CFBundleVersion</key>\n"
152 " <string>1.0</string>\n"
153 " <key>SecTaskAccess</key>\n"
154 " <array>\n"
155 " <string>allowed</string>\n"
156 " <string>debug</string>\n"
157 " </array>\n"
158 "</dict>\n"
159 "</plist>\n";
161 static void inferior_debug (int level, const char *fmt, ...)
162 ATTRIBUTE_PRINTF (2, 3);
164 static void
165 inferior_debug (int level, const char *fmt, ...)
167 va_list ap;
169 if (darwin_debug_flag < level)
170 return;
172 va_start (ap, fmt);
173 gdb_printf (gdb_stdlog, _("[%d inferior]: "), getpid ());
174 gdb_vprintf (gdb_stdlog, fmt, ap);
175 va_end (ap);
178 void
179 mach_check_error (kern_return_t ret, const char *file,
180 unsigned int line, const char *func)
182 if (ret == KERN_SUCCESS)
183 return;
184 if (func == NULL)
185 func = _("[UNKNOWN]");
187 warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
188 file, line, func, mach_error_string (ret), (unsigned long) ret);
191 static const char *
192 unparse_exception_type (unsigned int i)
194 static char unknown_exception_buf[32];
196 switch (i)
198 case EXC_BAD_ACCESS:
199 return "EXC_BAD_ACCESS";
200 case EXC_BAD_INSTRUCTION:
201 return "EXC_BAD_INSTRUCTION";
202 case EXC_ARITHMETIC:
203 return "EXC_ARITHMETIC";
204 case EXC_EMULATION:
205 return "EXC_EMULATION";
206 case EXC_SOFTWARE:
207 return "EXC_SOFTWARE";
208 case EXC_BREAKPOINT:
209 return "EXC_BREAKPOINT";
210 case EXC_SYSCALL:
211 return "EXC_SYSCALL";
212 case EXC_MACH_SYSCALL:
213 return "EXC_MACH_SYSCALL";
214 case EXC_RPC_ALERT:
215 return "EXC_RPC_ALERT";
216 case EXC_CRASH:
217 return "EXC_CRASH";
218 default:
219 snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
220 return unknown_exception_buf;
224 /* Set errno to zero, and then call ptrace with the given arguments.
225 If inferior debugging traces are on, then also print a debug
226 trace.
228 The returned value is the same as the value returned by ptrace,
229 except in the case where that value is -1 but errno is zero.
230 This case is documented to be a non-error situation, so we
231 return zero in that case. */
233 static int
234 darwin_ptrace (const char *name,
235 int request, int pid, caddr_t arg3, int arg4)
237 int ret;
239 errno = 0;
240 ret = ptrace (request, pid, arg3, arg4);
241 if (ret == -1 && errno == 0)
242 ret = 0;
244 inferior_debug (4, _("ptrace (%s, %d, 0x%lx, %d): %d (%s)\n"),
245 name, pid, (unsigned long) arg3, arg4, ret,
246 (ret != 0) ? safe_strerror (errno) : _("no error"));
247 return ret;
250 static int
251 cmp_thread_t (const void *l, const void *r)
253 thread_t tl = *(const thread_t *)l;
254 thread_t tr = *(const thread_t *)r;
255 return (int)(tl - tr);
258 void
259 darwin_nat_target::check_new_threads (inferior *inf)
261 kern_return_t kret;
262 thread_array_t thread_list;
263 unsigned int new_nbr;
264 unsigned int old_nbr;
265 unsigned int new_ix, old_ix;
266 darwin_inferior *darwin_inf = get_darwin_inferior (inf);
267 std::vector<darwin_thread_t *> new_thread_vec;
269 if (darwin_inf == nullptr)
270 return;
272 /* Get list of threads. */
273 kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
274 MACH_CHECK_ERROR (kret);
275 if (kret != KERN_SUCCESS)
276 return;
278 /* Sort the list. */
279 if (new_nbr > 1)
280 qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
282 old_nbr = darwin_inf->threads.size ();
284 /* Quick check for no changes. */
285 if (old_nbr == new_nbr)
287 size_t i;
289 for (i = 0; i < new_nbr; i++)
290 if (thread_list[i] != darwin_inf->threads[i]->gdb_port)
291 break;
292 if (i == new_nbr)
294 /* Deallocate ports. */
295 for (i = 0; i < new_nbr; i++)
297 kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
298 MACH_CHECK_ERROR (kret);
301 /* Deallocate the buffer. */
302 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
303 new_nbr * sizeof (int));
304 MACH_CHECK_ERROR (kret);
306 return;
310 /* Full handling: detect new threads, remove dead threads. */
312 new_thread_vec.reserve (new_nbr);
314 for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
316 thread_t new_id = (new_ix < new_nbr) ? thread_list[new_ix] : THREAD_NULL;
317 darwin_thread_t *old
318 = (old_ix < old_nbr) ? darwin_inf->threads[old_ix] : NULL;
319 thread_t old_id = old != NULL ? old->gdb_port : THREAD_NULL;
321 inferior_debug
322 (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
323 new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
325 if (old_id == new_id)
327 /* Thread still exist. */
328 new_thread_vec.push_back (old);
329 new_ix++;
330 old_ix++;
332 /* Deallocate the port. */
333 kret = mach_port_deallocate (gdb_task, new_id);
334 MACH_CHECK_ERROR (kret);
336 continue;
338 if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
340 /* Ignore dead ports.
341 In some weird cases, we might get dead ports. They should
342 correspond to dead thread so they could safely be ignored. */
343 new_ix++;
344 continue;
346 if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
348 /* A thread was created. */
349 darwin_thread_info *pti = new darwin_thread_info;
351 pti->gdb_port = new_id;
352 pti->msg_state = DARWIN_RUNNING;
354 /* Add the new thread. */
355 add_thread_with_info (this, ptid_t (inf->pid, 0, new_id),
356 private_thread_info_up (pti));
357 new_thread_vec.push_back (pti);
358 new_ix++;
359 continue;
361 if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
363 /* A thread was removed. */
364 struct thread_info *thr
365 = this->find_thread (ptid_t (inf->pid, 0, old_id));
366 delete_thread (thr);
367 kret = mach_port_deallocate (gdb_task, old_id);
368 MACH_CHECK_ERROR (kret);
369 old_ix++;
370 continue;
372 gdb_assert_not_reached ("unexpected thread case");
375 darwin_inf->threads = std::move (new_thread_vec);
377 /* Deallocate the buffer. */
378 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
379 new_nbr * sizeof (int));
380 MACH_CHECK_ERROR (kret);
383 /* Return an inferior by task port. */
384 static struct inferior *
385 darwin_find_inferior_by_task (task_t port)
387 for (inferior *inf : all_inferiors ())
389 darwin_inferior *priv = get_darwin_inferior (inf);
391 if (priv != nullptr && priv->task == port)
392 return inf;
394 return nullptr;
397 /* Return an inferior by pid port. */
398 static struct inferior *
399 darwin_find_inferior_by_pid (int pid)
401 for (inferior *inf : all_inferiors ())
403 if (inf->pid == pid)
404 return inf;
406 return nullptr;
409 /* Return a thread by port. */
410 static darwin_thread_t *
411 darwin_find_thread (struct inferior *inf, thread_t thread)
413 darwin_inferior *priv = get_darwin_inferior (inf);
415 if (priv != nullptr)
416 for (darwin_thread_t *t : priv->threads)
418 if (t->gdb_port == thread)
419 return t;
422 return NULL;
425 /* Suspend (ie stop) an inferior at Mach level. */
427 static void
428 darwin_suspend_inferior (struct inferior *inf)
430 darwin_inferior *priv = get_darwin_inferior (inf);
432 if (priv != nullptr && !priv->suspended)
434 kern_return_t kret;
436 kret = task_suspend (priv->task);
437 MACH_CHECK_ERROR (kret);
439 priv->suspended = 1;
443 /* Resume an inferior at Mach level. */
445 static void
446 darwin_resume_inferior (struct inferior *inf)
448 darwin_inferior *priv = get_darwin_inferior (inf);
450 if (priv != nullptr && priv->suspended)
452 kern_return_t kret;
454 kret = task_resume (priv->task);
455 MACH_CHECK_ERROR (kret);
457 priv->suspended = 0;
461 static void
462 darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
464 gdb_printf (gdb_stdlog,
465 _("message header:\n"));
466 gdb_printf (gdb_stdlog,
467 _(" bits: 0x%x\n"), hdr->msgh_bits);
468 gdb_printf (gdb_stdlog,
469 _(" size: 0x%x\n"), hdr->msgh_size);
470 gdb_printf (gdb_stdlog,
471 _(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
472 gdb_printf (gdb_stdlog,
473 _(" local-port: 0x%x\n"), hdr->msgh_local_port);
474 gdb_printf (gdb_stdlog,
475 _(" reserved: 0x%x\n"), hdr->msgh_reserved);
476 gdb_printf (gdb_stdlog,
477 _(" id: 0x%x\n"), hdr->msgh_id);
479 if (disp_body)
481 const unsigned char *data;
482 const unsigned int *ldata;
483 int size;
484 int i;
486 data = (unsigned char *)(hdr + 1);
487 size = hdr->msgh_size - sizeof (mach_msg_header_t);
489 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
491 mach_msg_body_t *bod = (mach_msg_body_t*)data;
492 mach_msg_port_descriptor_t *desc =
493 (mach_msg_port_descriptor_t *)(bod + 1);
494 int k;
495 NDR_record_t *ndr;
496 gdb_printf (gdb_stdlog,
497 _("body: descriptor_count=%u\n"),
498 bod->msgh_descriptor_count);
499 data += sizeof (mach_msg_body_t);
500 size -= sizeof (mach_msg_body_t);
501 for (k = 0; k < bod->msgh_descriptor_count; k++)
502 switch (desc[k].type)
504 case MACH_MSG_PORT_DESCRIPTOR:
505 gdb_printf
506 (gdb_stdlog,
507 _(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
508 k, desc[k].type, desc[k].name, desc[k].disposition);
509 break;
510 default:
511 gdb_printf (gdb_stdlog,
512 _(" descr %d: type=%u\n"),
513 k, desc[k].type);
514 break;
516 data += bod->msgh_descriptor_count
517 * sizeof (mach_msg_port_descriptor_t);
518 size -= bod->msgh_descriptor_count
519 * sizeof (mach_msg_port_descriptor_t);
520 ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
521 gdb_printf
522 (gdb_stdlog,
523 _("NDR: mig=%02x if=%02x encod=%02x "
524 "int=%02x char=%02x float=%02x\n"),
525 ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
526 ndr->int_rep, ndr->char_rep, ndr->float_rep);
527 data += sizeof (NDR_record_t);
528 size -= sizeof (NDR_record_t);
531 gdb_printf (gdb_stdlog, _(" data:"));
532 ldata = (const unsigned int *)data;
533 for (i = 0; i < size / sizeof (unsigned int); i++)
534 gdb_printf (gdb_stdlog, " %08x", ldata[i]);
535 gdb_printf (gdb_stdlog, _("\n"));
539 /* Adjust inferior data when a new task was created. */
541 static struct inferior *
542 darwin_find_new_inferior (task_t task_port, thread_t thread_port)
544 int task_pid;
545 struct inferior *inf;
546 kern_return_t kret;
547 mach_port_t prev;
549 /* Find the corresponding pid. */
550 kret = pid_for_task (task_port, &task_pid);
551 if (kret != KERN_SUCCESS)
553 MACH_CHECK_ERROR (kret);
554 return NULL;
557 /* Find the inferior for this pid. */
558 inf = darwin_find_inferior_by_pid (task_pid);
559 if (inf == NULL)
560 return NULL;
562 darwin_inferior *priv = get_darwin_inferior (inf);
564 /* Deallocate saved exception ports. */
565 darwin_deallocate_exception_ports (priv);
567 /* No need to remove dead_name notification, but still... */
568 kret = mach_port_request_notification (gdb_task, priv->task,
569 MACH_NOTIFY_DEAD_NAME, 0,
570 MACH_PORT_NULL,
571 MACH_MSG_TYPE_MAKE_SEND_ONCE,
572 &prev);
573 if (kret != KERN_INVALID_ARGUMENT)
574 MACH_CHECK_ERROR (kret);
576 /* Replace old task port. */
577 kret = mach_port_deallocate (gdb_task, priv->task);
578 MACH_CHECK_ERROR (kret);
579 priv->task = task_port;
581 darwin_setup_request_notification (inf);
582 darwin_setup_exceptions (inf);
584 return inf;
587 /* Check data representation. */
589 static int
590 darwin_check_message_ndr (NDR_record_t *ndr)
592 if (ndr->mig_vers != NDR_PROTOCOL_2_0
593 || ndr->if_vers != NDR_PROTOCOL_2_0
594 || ndr->mig_encoding != NDR_record.mig_encoding
595 || ndr->int_rep != NDR_record.int_rep
596 || ndr->char_rep != NDR_record.char_rep
597 || ndr->float_rep != NDR_record.float_rep)
598 return -1;
599 return 0;
602 /* Decode an exception message. */
605 darwin_nat_target::decode_exception_message (mach_msg_header_t *hdr,
606 inferior **pinf,
607 darwin_thread_t **pthread)
609 mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
610 mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
611 NDR_record_t *ndr;
612 integer_t *data;
613 struct inferior *inf;
614 darwin_thread_t *thread;
615 task_t task_port;
616 thread_t thread_port;
617 kern_return_t kret;
618 int i;
620 /* Check message destination. */
621 if (hdr->msgh_local_port != darwin_ex_port)
622 return -1;
624 /* Check message header. */
625 if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
626 return -1;
628 /* Check descriptors. */
629 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
630 + sizeof (*ndr) + 2 * sizeof (integer_t))
631 || bod->msgh_descriptor_count != 2
632 || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
633 || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
634 || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
635 || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
636 return -1;
638 /* Check data representation. */
639 ndr = (NDR_record_t *)(desc + 2);
640 if (darwin_check_message_ndr (ndr) != 0)
641 return -1;
643 /* Ok, the hard work. */
644 data = (integer_t *)(ndr + 1);
646 task_port = desc[1].name;
647 thread_port = desc[0].name;
649 /* Find process by port. */
650 inf = darwin_find_inferior_by_task (task_port);
651 *pinf = inf;
653 if (inf == NULL && data[0] == EXC_SOFTWARE && data[1] == 2
654 && data[2] == EXC_SOFT_SIGNAL && data[3] == SIGTRAP)
656 /* Not a known inferior, but a sigtrap. This happens on darwin 16.1.0,
657 as a new Mach task is created when a process exec. */
658 inf = darwin_find_new_inferior (task_port, thread_port);
659 *pinf = inf;
661 if (inf == NULL)
663 /* Deallocate task_port, unless it was saved. */
664 kret = mach_port_deallocate (mach_task_self (), task_port);
665 MACH_CHECK_ERROR (kret);
668 else
670 /* We got new rights to the task, get rid of it. Do not get rid of
671 thread right, as we will need it to find the thread. */
672 kret = mach_port_deallocate (mach_task_self (), task_port);
673 MACH_CHECK_ERROR (kret);
676 if (inf == NULL)
678 /* Not a known inferior. This could happen if the child fork, as
679 the created process will inherit its exception port.
680 FIXME: should the exception port be restored ? */
681 mig_reply_error_t reply;
683 inferior_debug
684 (4, _("darwin_decode_exception_message: unknown task 0x%x\n"),
685 task_port);
687 /* Free thread port (we don't know it). */
688 kret = mach_port_deallocate (mach_task_self (), thread_port);
689 MACH_CHECK_ERROR (kret);
691 darwin_encode_reply (&reply, hdr, KERN_SUCCESS);
693 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
694 reply.Head.msgh_size, 0,
695 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
696 MACH_PORT_NULL);
697 MACH_CHECK_ERROR (kret);
699 return 0;
702 /* Find thread by port. */
703 /* Check for new threads. Do it early so that the port in the exception
704 message can be deallocated. */
705 check_new_threads (inf);
707 /* Free the thread port (as gdb knows the thread, it has already has a right
708 for it, so this just decrement a reference counter). */
709 kret = mach_port_deallocate (mach_task_self (), thread_port);
710 MACH_CHECK_ERROR (kret);
712 thread = darwin_find_thread (inf, thread_port);
713 if (thread == NULL)
714 return -1;
715 *pthread = thread;
717 /* The thread should be running. However we have observed cases where a
718 thread got a SIGTTIN message after being stopped. */
719 gdb_assert (thread->msg_state != DARWIN_MESSAGE);
721 /* Finish decoding. */
722 thread->event.header = *hdr;
723 thread->event.thread_port = thread_port;
724 thread->event.task_port = task_port;
725 thread->event.ex_type = data[0];
726 thread->event.data_count = data[1];
728 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
729 + sizeof (*ndr) + 2 * sizeof (integer_t)
730 + data[1] * sizeof (integer_t)))
731 return -1;
732 for (i = 0; i < data[1]; i++)
733 thread->event.ex_data[i] = data[2 + i];
735 thread->msg_state = DARWIN_MESSAGE;
737 return 0;
740 /* Decode dead_name notify message. */
742 static int
743 darwin_decode_notify_message (mach_msg_header_t *hdr, struct inferior **pinf)
745 NDR_record_t *ndr = (NDR_record_t *)(hdr + 1);
746 integer_t *data = (integer_t *)(ndr + 1);
747 struct inferior *inf;
748 task_t task_port;
750 /* Check message header. */
751 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
752 return -1;
754 /* Check descriptors. */
755 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*ndr) + sizeof (integer_t)))
756 return -2;
758 /* Check data representation. */
759 if (darwin_check_message_ndr (ndr) != 0)
760 return -3;
762 task_port = data[0];
764 /* Find process by port. */
765 inf = darwin_find_inferior_by_task (task_port);
766 *pinf = inf;
768 /* Check message destination. */
769 if (inf != NULL)
771 darwin_inferior *priv = get_darwin_inferior (inf);
772 if (hdr->msgh_local_port != priv->notify_port)
773 return -4;
776 return 0;
779 static void
780 darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
781 integer_t code)
783 mach_msg_header_t *rh = &reply->Head;
785 rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
786 rh->msgh_remote_port = hdr->msgh_remote_port;
787 rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
788 rh->msgh_local_port = MACH_PORT_NULL;
789 rh->msgh_id = hdr->msgh_id + 100;
791 reply->NDR = NDR_record;
792 reply->RetCode = code;
795 static void
796 darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
798 kern_return_t kret;
799 mig_reply_error_t reply;
800 darwin_inferior *priv = get_darwin_inferior (inf);
802 darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
804 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
805 reply.Head.msgh_size, 0,
806 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
807 MACH_PORT_NULL);
808 MACH_CHECK_ERROR (kret);
810 priv->pending_messages--;
813 /* Wrapper around the __pthread_kill syscall. We use this instead of the
814 pthread_kill function to be able to send a signal to any kind of thread,
815 including GCD threads. */
817 static int
818 darwin_pthread_kill (darwin_thread_t *thread, int nsignal)
820 DIAGNOSTIC_PUSH;
821 DIAGNOSTIC_IGNORE_DEPRECATED_DECLARATIONS;
822 int res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
823 DIAGNOSTIC_POP;
824 return res;
827 static void
828 darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
829 int step, int nsignal)
831 inferior_debug
832 (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
833 thread->msg_state, thread->gdb_port, step, nsignal);
835 switch (thread->msg_state)
837 case DARWIN_MESSAGE:
838 if (thread->event.ex_type == EXC_SOFTWARE
839 && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
841 /* Either deliver a new signal or cancel the signal received. */
842 int res = PTRACE (PT_THUPDATE, inf->pid,
843 (caddr_t) (uintptr_t) thread->gdb_port, nsignal);
844 if (res < 0)
845 inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
847 else if (nsignal)
849 /* Note: ptrace is allowed only if the process is stopped.
850 Directly send the signal to the thread. */
851 int res = darwin_pthread_kill (thread, nsignal);
852 inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
853 thread->gdb_port, nsignal, res);
854 thread->signaled = 1;
857 /* Set or reset single step. */
858 inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
859 thread->gdb_port, step);
860 darwin_set_sstep (thread->gdb_port, step);
861 thread->single_step = step;
863 darwin_send_reply (inf, thread);
864 thread->msg_state = DARWIN_RUNNING;
865 break;
867 case DARWIN_RUNNING:
868 break;
870 case DARWIN_STOPPED:
871 kern_return_t kret = thread_resume (thread->gdb_port);
872 MACH_CHECK_ERROR (kret);
874 thread->msg_state = DARWIN_RUNNING;
875 break;
879 /* Resume all threads of the inferior. */
881 static void
882 darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
884 darwin_inferior *priv = get_darwin_inferior (inf);
886 if (priv != nullptr)
887 for (darwin_thread_t *thread : priv->threads)
888 darwin_resume_thread (inf, thread, step, nsignal);
891 /* Suspend all threads of INF. */
893 static void
894 darwin_suspend_inferior_threads (struct inferior *inf)
896 darwin_inferior *priv = get_darwin_inferior (inf);
898 for (darwin_thread_t *thread : priv->threads)
900 switch (thread->msg_state)
902 case DARWIN_STOPPED:
903 case DARWIN_MESSAGE:
904 break;
905 case DARWIN_RUNNING:
907 kern_return_t kret = thread_suspend (thread->gdb_port);
908 MACH_CHECK_ERROR (kret);
909 thread->msg_state = DARWIN_STOPPED;
910 break;
916 void
917 darwin_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signal)
919 int nsignal;
921 inferior_debug
922 (2, _("darwin_resume: ptid=%s, step=%d, signal=%d\n"),
923 ptid.to_string ().c_str (), step, signal);
925 if (signal == GDB_SIGNAL_0)
926 nsignal = 0;
927 else
928 nsignal = gdb_signal_to_host (signal);
930 /* Don't try to single step all threads. */
931 if (step)
932 ptid = inferior_ptid;
934 /* minus_one_ptid is RESUME_ALL. */
935 if (ptid == minus_one_ptid)
937 /* Resume threads. */
938 for (inferior *inf : all_inferiors ())
939 darwin_resume_inferior_threads (inf, step, nsignal);
941 /* Resume tasks. */
942 for (inferior *inf : all_inferiors ())
943 darwin_resume_inferior (inf);
945 else
947 inferior *inf = find_inferior_ptid (this, ptid);
948 long tid = ptid.tid ();
950 /* Stop the inferior (should be useless). */
951 darwin_suspend_inferior (inf);
953 if (tid == 0)
954 darwin_resume_inferior_threads (inf, step, nsignal);
955 else
957 darwin_thread_t *thread;
959 /* Suspend threads of the task. */
960 darwin_suspend_inferior_threads (inf);
962 /* Resume the selected thread. */
963 thread = darwin_find_thread (inf, tid);
964 gdb_assert (thread);
965 darwin_resume_thread (inf, thread, step, nsignal);
968 /* Resume the task. */
969 darwin_resume_inferior (inf);
973 ptid_t
974 darwin_nat_target::decode_message (mach_msg_header_t *hdr,
975 darwin_thread_t **pthread,
976 inferior **pinf,
977 target_waitstatus *status)
979 darwin_thread_t *thread;
980 struct inferior *inf;
982 /* Exception message. 2401 == 0x961 is exc. */
983 if (hdr->msgh_id == 2401)
985 int res;
987 /* Decode message. */
988 res = decode_exception_message (hdr, &inf, &thread);
990 if (res < 0)
992 /* Should not happen... */
993 warning (_("darwin_wait: ill-formatted message (id=0x%x)\n"),
994 hdr->msgh_id);
995 /* FIXME: send a failure reply? */
996 status->set_ignore ();
997 return minus_one_ptid;
999 if (inf == NULL)
1001 status->set_ignore ();
1002 return minus_one_ptid;
1004 *pinf = inf;
1005 *pthread = thread;
1007 darwin_inferior *priv = get_darwin_inferior (inf);
1009 priv->pending_messages++;
1011 thread->msg_state = DARWIN_MESSAGE;
1013 inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
1014 thread->gdb_port,
1015 unparse_exception_type (thread->event.ex_type));
1017 switch (thread->event.ex_type)
1019 case EXC_BAD_ACCESS:
1020 status->set_stopped (GDB_EXC_BAD_ACCESS);
1021 break;
1022 case EXC_BAD_INSTRUCTION:
1023 status->set_stopped (GDB_EXC_BAD_INSTRUCTION);
1024 break;
1025 case EXC_ARITHMETIC:
1026 status->set_stopped (GDB_EXC_ARITHMETIC);
1027 break;
1028 case EXC_EMULATION:
1029 status->set_stopped (GDB_EXC_EMULATION);
1030 break;
1031 case EXC_SOFTWARE:
1032 if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
1034 status->set_stopped
1035 (gdb_signal_from_host (thread->event.ex_data[1]));
1036 inferior_debug (5, _(" (signal %d: %s)\n"),
1037 thread->event.ex_data[1],
1038 gdb_signal_to_name (status->sig ()));
1040 /* If the thread is stopped because it has received a signal
1041 that gdb has just sent, continue. */
1042 if (thread->signaled)
1044 thread->signaled = 0;
1045 darwin_send_reply (inf, thread);
1046 thread->msg_state = DARWIN_RUNNING;
1047 status->set_ignore ();
1050 else
1051 status->set_stopped (GDB_EXC_SOFTWARE);
1052 break;
1053 case EXC_BREAKPOINT:
1054 /* Many internal GDB routines expect breakpoints to be reported
1055 as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
1056 as a spurious signal. */
1057 status->set_stopped (GDB_SIGNAL_TRAP);
1058 break;
1059 default:
1060 status->set_stopped (GDB_SIGNAL_UNKNOWN);
1061 break;
1064 return ptid_t (inf->pid, 0, thread->gdb_port);
1066 else if (hdr->msgh_id == 0x48)
1068 /* MACH_NOTIFY_DEAD_NAME: notification for exit *or* WIFSTOPPED. */
1069 int res;
1071 res = darwin_decode_notify_message (hdr, &inf);
1073 if (res < 0)
1075 /* Should not happen... */
1076 warning
1077 (_("darwin_wait: ill-formatted message (id=0x%x, res=%d)\n"),
1078 hdr->msgh_id, res);
1081 *pinf = NULL;
1082 *pthread = NULL;
1084 if (res < 0 || inf == NULL)
1086 status->set_ignore ();
1087 return minus_one_ptid;
1090 if (inf != NULL)
1092 darwin_inferior *priv = get_darwin_inferior (inf);
1094 if (!priv->no_ptrace)
1096 pid_t res_pid;
1097 int wstatus;
1099 res_pid = wait4 (inf->pid, &wstatus, 0, NULL);
1100 if (res_pid < 0 || res_pid != inf->pid)
1102 warning (_("wait4: res=%d: %s\n"),
1103 res_pid, safe_strerror (errno));
1104 status->set_ignore ();
1105 return minus_one_ptid;
1107 if (WIFEXITED (wstatus))
1109 status->set_exited (WEXITSTATUS (wstatus));
1110 inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
1111 res_pid, wstatus);
1113 else if (WIFSTOPPED (wstatus))
1115 /* Ignore stopped state, it will be handled by the next
1116 exception. */
1117 status->set_ignore ();
1118 inferior_debug (4, _("darwin_wait: pid %d received WIFSTOPPED\n"),
1119 res_pid);
1120 return minus_one_ptid;
1122 else if (WIFSIGNALED (wstatus))
1124 status->set_signalled
1125 (gdb_signal_from_host (WTERMSIG (wstatus)));
1126 inferior_debug (4, _("darwin_wait: pid=%d received signal %d\n"),
1127 res_pid, status->sig());
1129 else
1131 status->set_ignore ();
1132 warning (_("Unexpected wait status after MACH_NOTIFY_DEAD_NAME "
1133 "notification: 0x%x"), wstatus);
1134 return minus_one_ptid;
1137 return ptid_t (inf->pid);
1139 else
1141 inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
1142 status->set_exited (0 /* Don't know. */);
1143 return ptid_t (inf->pid, 0, 0);
1148 /* Unknown message. */
1149 warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
1150 status->set_ignore ();
1151 return minus_one_ptid;
1155 darwin_nat_target::cancel_breakpoint (inferior *inf, ptid_t ptid)
1157 /* Arrange for a breakpoint to be hit again later. We will handle
1158 the current event, eventually we will resume this thread, and this
1159 breakpoint will trap again.
1161 If we do not do this, then we run the risk that the user will
1162 delete or disable the breakpoint, but the thread will have already
1163 tripped on it. */
1165 struct regcache *regcache = get_thread_regcache (this, ptid);
1166 struct gdbarch *gdbarch = regcache->arch ();
1167 CORE_ADDR pc;
1169 pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
1170 if (breakpoint_inserted_here_p (inf->aspace.get (), pc))
1172 inferior_debug (4, "cancel_breakpoint for thread 0x%lx\n",
1173 (unsigned long) ptid.tid ());
1175 /* Back up the PC if necessary. */
1176 if (gdbarch_decr_pc_after_break (gdbarch))
1177 regcache_write_pc (regcache, pc);
1179 return 1;
1181 return 0;
1184 ptid_t
1185 darwin_nat_target::wait_1 (ptid_t ptid, struct target_waitstatus *status)
1187 kern_return_t kret;
1188 union
1190 mach_msg_header_t hdr;
1191 char data[0x100];
1192 } msgin;
1193 mach_msg_header_t *hdr = &msgin.hdr;
1194 ptid_t res;
1195 darwin_thread_t *thread;
1197 inferior_debug
1198 (2, _("darwin_wait: waiting for a message ptid=%s\n"),
1199 ptid.to_string ().c_str ());
1201 /* Handle fake stop events at first. */
1202 if (darwin_inf_fake_stop != NULL)
1204 inferior *inf = darwin_inf_fake_stop;
1205 darwin_inf_fake_stop = NULL;
1207 darwin_inferior *priv = get_darwin_inferior (inf);
1209 status->set_stopped (GDB_SIGNAL_TRAP);
1210 thread = priv->threads[0];
1211 thread->msg_state = DARWIN_STOPPED;
1212 return ptid_t (inf->pid, 0, thread->gdb_port);
1217 /* set_sigint_trap (); */
1219 /* Wait for a message. */
1220 kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1221 sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1223 /* clear_sigint_trap (); */
1225 if (kret == MACH_RCV_INTERRUPTED)
1227 status->set_ignore ();
1228 return minus_one_ptid;
1231 if (kret != MACH_MSG_SUCCESS)
1233 inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
1234 status->set_spurious ();
1235 return minus_one_ptid;
1238 /* Debug: display message. */
1239 if (darwin_debug_flag > 10)
1240 darwin_dump_message (hdr, darwin_debug_flag > 11);
1242 inferior *inf;
1243 res = decode_message (hdr, &thread, &inf, status);
1244 if (res == minus_one_ptid)
1245 continue;
1247 /* Early return in case an inferior has exited. */
1248 if (inf == NULL)
1249 return res;
1251 while (status->kind () == TARGET_WAITKIND_IGNORE);
1253 /* Stop all tasks. */
1254 for (inferior *inf : all_inferiors (this))
1256 darwin_suspend_inferior (inf);
1257 check_new_threads (inf);
1260 /* Read pending messages. */
1261 while (1)
1263 struct target_waitstatus status2;
1264 ptid_t ptid2;
1266 kret = mach_msg (&msgin.hdr,
1267 MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1268 sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1270 if (kret == MACH_RCV_TIMED_OUT)
1271 break;
1272 if (kret != MACH_MSG_SUCCESS)
1274 inferior_debug
1275 (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
1276 break;
1279 /* Debug: display message. */
1280 if (darwin_debug_flag > 10)
1281 darwin_dump_message (hdr, darwin_debug_flag > 11);
1283 inferior *inf;
1284 ptid2 = decode_message (hdr, &thread, &inf, &status2);
1286 if (inf != NULL && thread != NULL
1287 && thread->event.ex_type == EXC_BREAKPOINT)
1289 if (thread->single_step
1290 || cancel_breakpoint (inf,
1291 ptid_t (inf->pid, 0, thread->gdb_port)))
1293 gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1294 darwin_send_reply (inf, thread);
1295 thread->msg_state = DARWIN_RUNNING;
1297 else
1298 inferior_debug
1299 (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
1300 thread->gdb_port);
1302 else
1303 inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1305 return res;
1308 ptid_t
1309 darwin_nat_target::wait (ptid_t ptid, struct target_waitstatus *status,
1310 target_wait_flags options)
1312 return wait_1 (ptid, status);
1315 void
1316 darwin_nat_target::interrupt ()
1318 struct inferior *inf = current_inferior ();
1319 darwin_inferior *priv = get_darwin_inferior (inf);
1321 /* FIXME: handle in no_ptrace mode. */
1322 gdb_assert (!priv->no_ptrace);
1323 ::kill (inf->pid, SIGINT);
1326 /* Deallocate threads port and vector. */
1328 static void
1329 darwin_deallocate_threads (struct inferior *inf)
1331 darwin_inferior *priv = get_darwin_inferior (inf);
1333 for (darwin_thread_t *t : priv->threads)
1335 kern_return_t kret = mach_port_deallocate (gdb_task, t->gdb_port);
1336 MACH_CHECK_ERROR (kret);
1339 priv->threads.clear ();
1342 void
1343 darwin_nat_target::mourn_inferior ()
1345 struct inferior *inf = current_inferior ();
1346 darwin_inferior *priv = get_darwin_inferior (inf);
1347 kern_return_t kret;
1348 mach_port_t prev;
1350 /* Deallocate threads. */
1351 darwin_deallocate_threads (inf);
1353 /* Remove notify_port from darwin_port_set. */
1354 kret = mach_port_move_member (gdb_task,
1355 priv->notify_port, MACH_PORT_NULL);
1356 MACH_CHECK_ERROR (kret);
1358 /* Remove task port dead_name notification. */
1359 kret = mach_port_request_notification (gdb_task, priv->task,
1360 MACH_NOTIFY_DEAD_NAME, 0,
1361 MACH_PORT_NULL,
1362 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1363 &prev);
1364 /* This can fail if the task is dead. */
1365 inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
1366 priv->task, prev, priv->notify_port);
1368 if (kret == KERN_SUCCESS)
1370 kret = mach_port_deallocate (gdb_task, prev);
1371 MACH_CHECK_ERROR (kret);
1374 /* Destroy notify_port. */
1375 kret = mach_port_destroy (gdb_task, priv->notify_port);
1376 MACH_CHECK_ERROR (kret);
1378 /* Deallocate saved exception ports. */
1379 darwin_deallocate_exception_ports (priv);
1381 /* Deallocate task port. */
1382 kret = mach_port_deallocate (gdb_task, priv->task);
1383 MACH_CHECK_ERROR (kret);
1385 inf->priv = NULL;
1387 inf_child_target::mourn_inferior ();
1390 static void
1391 darwin_reply_to_all_pending_messages (struct inferior *inf)
1393 darwin_inferior *priv = get_darwin_inferior (inf);
1395 for (darwin_thread_t *t : priv->threads)
1397 if (t->msg_state == DARWIN_MESSAGE)
1398 darwin_resume_thread (inf, t, 0, 0);
1402 void
1403 darwin_nat_target::stop_inferior (inferior *inf)
1405 struct target_waitstatus wstatus;
1406 ptid_t ptid;
1407 int res;
1408 darwin_inferior *priv = get_darwin_inferior (inf);
1410 gdb_assert (inf != NULL);
1412 darwin_suspend_inferior (inf);
1414 darwin_reply_to_all_pending_messages (inf);
1416 if (priv->no_ptrace)
1417 return;
1419 res = ::kill (inf->pid, SIGSTOP);
1420 if (res != 0)
1421 warning (_("cannot kill: %s"), safe_strerror (errno));
1423 /* Wait until the process is really stopped. */
1424 while (1)
1426 ptid = wait_1 (ptid_t (inf->pid), &wstatus);
1427 if (wstatus.kind () == TARGET_WAITKIND_STOPPED
1428 && wstatus.sig () == GDB_SIGNAL_STOP)
1429 break;
1433 static kern_return_t
1434 darwin_save_exception_ports (darwin_inferior *inf)
1436 kern_return_t kret;
1438 inf->exception_info.count =
1439 sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1441 kret = task_get_exception_ports
1442 (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1443 &inf->exception_info.count, inf->exception_info.ports,
1444 inf->exception_info.behaviors, inf->exception_info.flavors);
1445 return kret;
1448 static kern_return_t
1449 darwin_restore_exception_ports (darwin_inferior *inf)
1451 int i;
1452 kern_return_t kret;
1454 for (i = 0; i < inf->exception_info.count; i++)
1456 kret = task_set_exception_ports
1457 (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1458 inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1459 if (kret != KERN_SUCCESS)
1460 return kret;
1463 return KERN_SUCCESS;
1466 /* Deallocate saved exception ports. */
1468 static void
1469 darwin_deallocate_exception_ports (darwin_inferior *inf)
1471 int i;
1472 kern_return_t kret;
1474 for (i = 0; i < inf->exception_info.count; i++)
1476 kret = mach_port_deallocate (gdb_task, inf->exception_info.ports[i]);
1477 MACH_CHECK_ERROR (kret);
1479 inf->exception_info.count = 0;
1482 static void
1483 darwin_setup_exceptions (struct inferior *inf)
1485 darwin_inferior *priv = get_darwin_inferior (inf);
1486 kern_return_t kret;
1487 exception_mask_t mask;
1489 kret = darwin_save_exception_ports (priv);
1490 if (kret != KERN_SUCCESS)
1491 error (_("Unable to save exception ports, task_get_exception_ports"
1492 "returned: %d"),
1493 kret);
1495 /* Set exception port. */
1496 if (enable_mach_exceptions)
1497 mask = EXC_MASK_ALL;
1498 else
1499 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1500 kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
1501 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1502 if (kret != KERN_SUCCESS)
1503 error (_("Unable to set exception ports, task_set_exception_ports"
1504 "returned: %d"),
1505 kret);
1508 void
1509 darwin_nat_target::kill ()
1511 struct inferior *inf = current_inferior ();
1512 darwin_inferior *priv = get_darwin_inferior (inf);
1513 struct target_waitstatus wstatus;
1514 ptid_t ptid;
1515 kern_return_t kret;
1516 int res;
1518 if (inferior_ptid == null_ptid)
1519 return;
1521 gdb_assert (inf != NULL);
1523 kret = darwin_restore_exception_ports (priv);
1524 MACH_CHECK_ERROR (kret);
1526 darwin_reply_to_all_pending_messages (inf);
1528 res = ::kill (inf->pid, 9);
1530 if (res == 0)
1532 /* On MacOS version Sierra, the darwin_restore_exception_ports call
1533 does not work as expected.
1534 When the kill function is called, the SIGKILL signal is received
1535 by gdb whereas it should have been received by the kernel since
1536 the exception ports have been restored.
1537 This behavior is not the expected one thus gdb does not reply to
1538 the received SIGKILL message. This situation leads to a "busy"
1539 resource from the kernel point of view and the inferior is never
1540 released, causing it to remain as a zombie process, even after
1541 GDB exits.
1542 To work around this, we mark all the threads of the inferior as
1543 signaled thus darwin_decode_message function knows that the kill
1544 signal was sent by gdb and will take the appropriate action
1545 (cancel signal and reply to the signal message). */
1546 for (darwin_thread_t *thread : priv->threads)
1547 thread->signaled = 1;
1549 darwin_resume_inferior (inf);
1551 ptid = wait_1 (ptid_t (inf->pid), &wstatus);
1553 else if (errno != ESRCH)
1554 warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
1555 inf->pid, safe_strerror (errno));
1557 target_mourn_inferior (ptid_t (inf->pid));
1560 static void
1561 darwin_setup_request_notification (struct inferior *inf)
1563 darwin_inferior *priv = get_darwin_inferior (inf);
1564 kern_return_t kret;
1565 mach_port_t prev_not;
1567 kret = mach_port_request_notification (gdb_task, priv->task,
1568 MACH_NOTIFY_DEAD_NAME, 0,
1569 priv->notify_port,
1570 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1571 &prev_not);
1572 if (kret != KERN_SUCCESS)
1573 error (_("Termination notification request failed, "
1574 "mach_port_request_notification\n"
1575 "returned: %d"),
1576 kret);
1577 if (prev_not != MACH_PORT_NULL)
1579 /* This is unexpected, as there should not be any previously
1580 registered notification request. But this is not a fatal
1581 issue, so just emit a warning. */
1582 warning (_("\
1583 A task termination request was registered before the debugger registered\n\
1584 its own. This is unexpected, but should otherwise not have any actual\n\
1585 impact on the debugging session."));
1589 static void
1590 darwin_attach_pid (struct inferior *inf)
1592 kern_return_t kret;
1594 darwin_inferior *priv = new darwin_inferior;
1595 inf->priv.reset (priv);
1599 kret = task_for_pid (gdb_task, inf->pid, &priv->task);
1600 if (kret != KERN_SUCCESS)
1602 int status;
1604 if (!inf->attach_flag)
1606 kill (inf->pid, 9);
1607 waitpid (inf->pid, &status, 0);
1610 error
1611 (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
1612 " (please check gdb is codesigned - see taskgated(8))"),
1613 inf->pid, mach_error_string (kret), (unsigned long) kret);
1616 inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1617 priv->task, inf->pid);
1619 if (darwin_ex_port == MACH_PORT_NULL)
1621 /* Create a port to get exceptions. */
1622 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1623 &darwin_ex_port);
1624 if (kret != KERN_SUCCESS)
1625 error (_("Unable to create exception port, mach_port_allocate "
1626 "returned: %d"),
1627 kret);
1629 kret = mach_port_insert_right (gdb_task, darwin_ex_port,
1630 darwin_ex_port,
1631 MACH_MSG_TYPE_MAKE_SEND);
1632 if (kret != KERN_SUCCESS)
1633 error (_("Unable to create exception port, mach_port_insert_right "
1634 "returned: %d"),
1635 kret);
1637 /* Create a port set and put ex_port in it. */
1638 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1639 &darwin_port_set);
1640 if (kret != KERN_SUCCESS)
1641 error (_("Unable to create port set, mach_port_allocate "
1642 "returned: %d"),
1643 kret);
1645 kret = mach_port_move_member (gdb_task, darwin_ex_port,
1646 darwin_port_set);
1647 if (kret != KERN_SUCCESS)
1648 error (_("Unable to move exception port into new port set, "
1649 "mach_port_move_member\n"
1650 "returned: %d"),
1651 kret);
1654 /* Create a port to be notified when the child task terminates. */
1655 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1656 &priv->notify_port);
1657 if (kret != KERN_SUCCESS)
1658 error (_("Unable to create notification port, mach_port_allocate "
1659 "returned: %d"),
1660 kret);
1662 kret = mach_port_move_member (gdb_task,
1663 priv->notify_port, darwin_port_set);
1664 if (kret != KERN_SUCCESS)
1665 error (_("Unable to move notification port into new port set, "
1666 "mach_port_move_member\n"
1667 "returned: %d"),
1668 kret);
1670 darwin_setup_request_notification (inf);
1672 darwin_setup_exceptions (inf);
1674 catch (const gdb_exception &ex)
1676 exit_inferior (inf);
1677 switch_to_no_thread ();
1679 throw;
1682 target_ops *darwin_ops = get_native_target ();
1683 if (!inf->target_is_pushed (darwin_ops))
1684 inf->push_target (darwin_ops);
1687 /* Get the thread_info object corresponding to this darwin_thread_info. */
1689 static struct thread_info *
1690 thread_info_from_private_thread_info (darwin_thread_info *pti)
1692 for (struct thread_info *it : all_threads ())
1694 darwin_thread_info *iter_pti = get_darwin_thread_info (it);
1696 if (iter_pti->gdb_port == pti->gdb_port)
1697 return it;
1700 gdb_assert_not_reached ("did not find gdb thread for darwin thread");
1703 void
1704 darwin_nat_target::init_thread_list (inferior *inf)
1706 check_new_threads (inf);
1708 darwin_inferior *priv = get_darwin_inferior (inf);
1710 gdb_assert (!priv->threads.empty ());
1712 darwin_thread_info *first_pti = priv->threads.front ();
1713 struct thread_info *first_thread
1714 = thread_info_from_private_thread_info (first_pti);
1716 switch_to_thread (first_thread);
1719 /* The child must synchronize with gdb: gdb must set the exception port
1720 before the child call PTRACE_SIGEXC. We use a pipe to achieve this.
1721 FIXME: is there a lighter way ? */
1722 static int ptrace_fds[2];
1724 static void
1725 darwin_ptrace_me (void)
1727 int res;
1728 char c;
1730 /* Close write end point. */
1731 if (close (ptrace_fds[1]) < 0)
1732 trace_start_error_with_name ("close");
1734 /* Wait until gdb is ready. */
1735 res = read (ptrace_fds[0], &c, 1);
1736 if (res != 0)
1737 trace_start_error (_("unable to read from pipe, read returned: %d"), res);
1739 if (close (ptrace_fds[0]) < 0)
1740 trace_start_error_with_name ("close");
1742 /* Get rid of privileges. */
1743 if (setegid (getgid ()) < 0)
1744 trace_start_error_with_name ("setegid");
1746 /* Set TRACEME. */
1747 if (PTRACE (PT_TRACE_ME, 0, 0, 0) < 0)
1748 trace_start_error_with_name ("PTRACE");
1750 /* Redirect signals to exception port. */
1751 if (PTRACE (PT_SIGEXC, 0, 0, 0) < 0)
1752 trace_start_error_with_name ("PTRACE");
1755 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2). */
1756 static void
1757 darwin_pre_ptrace (void)
1759 if (pipe (ptrace_fds) != 0)
1761 ptrace_fds[0] = -1;
1762 ptrace_fds[1] = -1;
1763 error (_("unable to create a pipe: %s"), safe_strerror (errno));
1766 mark_fd_no_cloexec (ptrace_fds[0]);
1767 mark_fd_no_cloexec (ptrace_fds[1]);
1770 void
1771 darwin_nat_target::ptrace_him (int pid)
1773 struct inferior *inf = current_inferior ();
1775 darwin_attach_pid (inf);
1777 /* Let's the child run. */
1778 ::close (ptrace_fds[0]);
1779 ::close (ptrace_fds[1]);
1781 unmark_fd_no_cloexec (ptrace_fds[0]);
1782 unmark_fd_no_cloexec (ptrace_fds[1]);
1784 init_thread_list (inf);
1786 gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
1789 static void
1790 darwin_execvp (const char *file, char * const argv[], char * const env[])
1792 posix_spawnattr_t attr;
1793 short ps_flags = 0;
1794 int res;
1796 res = posix_spawnattr_init (&attr);
1797 if (res != 0)
1799 gdb_printf
1800 (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
1801 return;
1804 /* Do like execve: replace the image. */
1805 ps_flags = POSIX_SPAWN_SETEXEC;
1807 /* Disable ASLR. The constant doesn't look to be available outside the
1808 kernel include files. */
1809 #ifndef _POSIX_SPAWN_DISABLE_ASLR
1810 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
1811 #endif
1812 ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
1813 res = posix_spawnattr_setflags (&attr, ps_flags);
1814 if (res != 0)
1816 gdb_printf (gdb_stderr, "Cannot set posix_spawn flags\n");
1817 return;
1820 posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
1823 /* Read kernel version, and return TRUE if this host may have System
1824 Integrity Protection (Sierra or later). */
1826 static bool
1827 may_have_sip ()
1829 char str[16];
1830 size_t sz = sizeof (str);
1831 int ret;
1833 ret = sysctlbyname ("kern.osrelease", str, &sz, NULL, 0);
1834 if (ret == 0 && sz < sizeof (str))
1836 unsigned long ver = strtoul (str, NULL, 10);
1837 if (ver >= 16)
1838 return true;
1840 return false;
1843 /* A helper for maybe_cache_shell. This copies the shell to the
1844 cache. It will throw an exception on any failure. */
1846 static void
1847 copy_shell_to_cache (const char *shell, const std::string &new_name)
1849 scoped_fd from_fd = gdb_open_cloexec (shell, O_RDONLY, 0);
1850 if (from_fd.get () < 0)
1851 error (_("Could not open shell (%s) for reading: %s"),
1852 shell, safe_strerror (errno));
1854 std::string new_dir = ldirname (new_name.c_str ());
1855 if (!mkdir_recursive (new_dir.c_str ()))
1856 error (_("Could not make cache directory \"%s\": %s"),
1857 new_dir.c_str (), safe_strerror (errno));
1859 gdb::char_vector temp_name = make_temp_filename (new_name);
1860 scoped_fd to_fd = gdb_mkostemp_cloexec (&temp_name[0]);
1861 gdb::unlinker unlink_file_on_error (temp_name.data ());
1863 if (to_fd.get () < 0)
1864 error (_("Could not open temporary file \"%s\" for writing: %s"),
1865 temp_name.data (), safe_strerror (errno));
1867 if (fcopyfile (from_fd.get (), to_fd.get (), nullptr,
1868 COPYFILE_STAT | COPYFILE_DATA) != 0)
1869 error (_("Could not copy shell to cache as \"%s\": %s"),
1870 temp_name.data (), safe_strerror (errno));
1872 /* Be sure that the caching is atomic so that we don't get bad
1873 results from multiple copies of gdb running at the same time. */
1874 if (rename (temp_name.data (), new_name.c_str ()) != 0)
1875 error (_("Could not rename shell cache file to \"%s\": %s"),
1876 new_name.c_str (), safe_strerror (errno));
1878 unlink_file_on_error.keep ();
1881 /* If $SHELL is restricted, try to cache a copy. Starting with El
1882 Capitan, macOS introduced System Integrity Protection. Among other
1883 things, this prevents certain executables from being ptrace'd. In
1884 particular, executables in /bin, like most shells, are affected.
1885 To work around this, while preserving command-line glob expansion
1886 and redirections, gdb will cache a copy of the shell. Return true
1887 if all is well -- either the shell is not subject to SIP or it has
1888 been successfully cached. Returns false if something failed. */
1890 static bool
1891 maybe_cache_shell ()
1893 /* SF_RESTRICTED is defined in sys/stat.h and lets us determine if a
1894 given file is subject to SIP. */
1895 #ifdef SF_RESTRICTED
1897 /* If a check fails we want to revert -- maybe the user deleted the
1898 cache while gdb was running, or something like that. */
1899 copied_shell = nullptr;
1901 const char *shell = get_shell ();
1902 if (!IS_ABSOLUTE_PATH (shell))
1904 warning (_("This version of macOS has System Integrity Protection.\n\
1905 Normally gdb would try to work around this by caching a copy of your shell,\n\
1906 but because your shell (%s) is not an absolute path, this is being skipped."),
1907 shell);
1908 return false;
1911 struct stat sb;
1912 if (stat (shell, &sb) < 0)
1914 warning (_("This version of macOS has System Integrity Protection.\n\
1915 Normally gdb would try to work around this by caching a copy of your shell,\n\
1916 but because gdb could not stat your shell (%s), this is being skipped.\n\
1917 The error was: %s"),
1918 shell, safe_strerror (errno));
1919 return false;
1922 if ((sb.st_flags & SF_RESTRICTED) == 0)
1923 return true;
1925 /* Put the copy somewhere like ~/Library/Caches/gdb/bin/sh. */
1926 std::string new_name = get_standard_cache_dir ();
1927 /* There's no need to insert a directory separator here, because
1928 SHELL is known to be absolute. */
1929 new_name.append (shell);
1931 /* Maybe it was cached by some earlier gdb. */
1932 if (stat (new_name.c_str (), &sb) != 0 || !S_ISREG (sb.st_mode))
1936 copy_shell_to_cache (shell, new_name);
1938 catch (const gdb_exception_error &ex)
1940 warning (_("This version of macOS has System Integrity Protection.\n\
1941 Because `startup-with-shell' is enabled, gdb tried to work around SIP by\n\
1942 caching a copy of your shell. However, this failed:\n\
1943 %s\n\
1944 If you correct the problem, gdb will automatically try again the next time\n\
1945 you \"run\". To prevent these attempts, you can use:\n\
1946 set startup-with-shell off"),
1947 ex.what ());
1948 return false;
1951 gdb_printf (_("Note: this version of macOS has System Integrity Protection.\n\
1952 Because `startup-with-shell' is enabled, gdb has worked around this by\n\
1953 caching a copy of your shell. The shell used by \"run\" is now:\n\
1954 %s\n"),
1955 new_name.c_str ());
1958 /* We need to make sure that the new name has the correct lifetime. */
1959 static std::string saved_shell = std::move (new_name);
1960 copied_shell = saved_shell.c_str ();
1962 #endif /* SF_RESTRICTED */
1964 return true;
1967 void
1968 darwin_nat_target::create_inferior (const char *exec_file,
1969 const std::string &allargs,
1970 char **env, int from_tty)
1972 if (exec_file == nullptr)
1973 no_executable_specified_error ();
1975 std::optional<scoped_restore_tmpl<bool>> restore_startup_with_shell;
1976 darwin_nat_target *the_target = this;
1978 if (startup_with_shell && may_have_sip ())
1980 if (!maybe_cache_shell ())
1982 warning (_("startup-with-shell is now temporarily disabled"));
1983 restore_startup_with_shell.emplace (&startup_with_shell, 0);
1987 /* Do the hard work. */
1988 fork_inferior (exec_file, allargs, env, darwin_ptrace_me,
1989 [the_target] (int pid)
1991 the_target->ptrace_him (pid);
1993 darwin_pre_ptrace, copied_shell,
1994 darwin_execvp);
1998 /* Set things up such that the next call to darwin_wait will immediately
1999 return a fake stop event for inferior INF.
2001 This assumes that the inferior's thread list has been initialized,
2002 as it will suspend the inferior's first thread. */
2004 static void
2005 darwin_setup_fake_stop_event (struct inferior *inf)
2007 darwin_inferior *priv = get_darwin_inferior (inf);
2008 darwin_thread_t *thread;
2009 kern_return_t kret;
2011 gdb_assert (darwin_inf_fake_stop == NULL);
2012 darwin_inf_fake_stop = inf;
2014 /* When detecting a fake pending stop event, darwin_wait returns
2015 an event saying that the first thread is in a DARWIN_STOPPED
2016 state. To make that accurate, we need to suspend that thread
2017 as well. Otherwise, we'll try resuming it when resuming the
2018 inferior, and get a warning because the thread's suspend count
2019 is already zero, making the resume request useless. */
2020 thread = priv->threads[0];
2021 kret = thread_suspend (thread->gdb_port);
2022 MACH_CHECK_ERROR (kret);
2025 /* Attach to process PID, then initialize for debugging it
2026 and wait for the trace-trap that results from attaching. */
2027 void
2028 darwin_nat_target::attach (const char *args, int from_tty)
2030 pid_t pid;
2031 struct inferior *inf;
2033 pid = parse_pid_to_attach (args);
2035 if (pid == getpid ())
2036 error (_("I refuse to debug myself!"));
2038 target_announce_attach (from_tty, pid);
2040 if (pid == 0 || ::kill (pid, 0) < 0)
2041 error (_("Can't attach to process %d: %s (%d)"),
2042 pid, safe_strerror (errno), errno);
2044 inf = current_inferior ();
2045 inferior_appeared (inf, pid);
2046 inf->attach_flag = true;
2048 darwin_attach_pid (inf);
2050 darwin_suspend_inferior (inf);
2052 init_thread_list (inf);
2054 darwin_inferior *priv = get_darwin_inferior (inf);
2056 darwin_check_osabi (priv, inferior_ptid.tid ());
2058 darwin_setup_fake_stop_event (inf);
2060 priv->no_ptrace = 1;
2063 /* Take a program previously attached to and detaches it.
2064 The program resumes execution and will no longer stop
2065 on signals, etc. We'd better not have left any breakpoints
2066 in the program or it'll die when it hits one. For this
2067 to work, it may be necessary for the process to have been
2068 previously attached. It *might* work if the program was
2069 started via fork. */
2071 void
2072 darwin_nat_target::detach (inferior *inf, int from_tty)
2074 darwin_inferior *priv = get_darwin_inferior (inf);
2075 kern_return_t kret;
2076 int res;
2078 /* Display message. */
2079 target_announce_detach (from_tty);
2081 /* If ptrace() is in use, stop the process. */
2082 if (!priv->no_ptrace)
2083 stop_inferior (inf);
2085 kret = darwin_restore_exception_ports (priv);
2086 MACH_CHECK_ERROR (kret);
2088 if (!priv->no_ptrace)
2090 res = PTRACE (PT_DETACH, inf->pid, 0, 0);
2091 if (res != 0)
2092 warning (_("Unable to detach from process-id %d: %s (%d)"),
2093 inf->pid, safe_strerror (errno), errno);
2096 darwin_reply_to_all_pending_messages (inf);
2098 /* When using ptrace, we have just performed a PT_DETACH, which
2099 resumes the inferior. On the other hand, when we are not using
2100 ptrace, we need to resume its execution ourselves. */
2101 if (priv->no_ptrace)
2102 darwin_resume_inferior (inf);
2104 mourn_inferior ();
2107 std::string
2108 darwin_nat_target::pid_to_str (ptid_t ptid)
2110 long tid = ptid.tid ();
2112 if (tid != 0)
2113 return string_printf (_("Thread 0x%lx of process %u"),
2114 tid, ptid.pid ());
2116 return normal_pid_to_str (ptid);
2119 bool
2120 darwin_nat_target::thread_alive (ptid_t ptid)
2122 return true;
2125 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
2126 copy it to RDADDR in gdb's address space.
2127 If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
2128 to ADDR in inferior task's address space.
2129 Return 0 on failure; number of bytes read / written otherwise. */
2131 static int
2132 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
2133 gdb_byte *rdaddr, const gdb_byte *wraddr,
2134 ULONGEST length)
2136 kern_return_t kret;
2137 mach_vm_size_t res_length = 0;
2139 inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
2140 task, core_addr_to_string (addr), pulongest (length));
2142 /* First read. */
2143 if (rdaddr != NULL)
2145 mach_vm_size_t count;
2147 /* According to target.h(to_xfer_partial), one and only one may be
2148 non-null. */
2149 gdb_assert (wraddr == NULL);
2151 kret = mach_vm_read_overwrite (task, addr, length,
2152 (mach_vm_address_t) rdaddr, &count);
2153 if (kret != KERN_SUCCESS)
2155 inferior_debug
2156 (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
2157 core_addr_to_string (addr), mach_error_string (kret));
2158 return 0;
2160 return count;
2163 /* See above. */
2164 gdb_assert (wraddr != NULL);
2166 while (length != 0)
2168 mach_vm_address_t offset = addr & (mach_page_size - 1);
2169 mach_vm_address_t region_address = (mach_vm_address_t) (addr - offset);
2170 mach_vm_size_t aligned_length =
2171 (mach_vm_size_t) PAGE_ROUND (offset + length);
2172 vm_region_submap_short_info_data_64_t info;
2173 mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
2174 natural_t region_depth = 1000;
2175 mach_vm_address_t region_start = region_address;
2176 mach_vm_size_t region_length;
2177 mach_vm_size_t write_length;
2179 /* Read page protection. */
2180 kret = mach_vm_region_recurse
2181 (task, &region_start, &region_length, &region_depth,
2182 (vm_region_recurse_info_t) &info, &count);
2184 if (kret != KERN_SUCCESS)
2186 inferior_debug (1, _("darwin_read_write_inferior: "
2187 "mach_vm_region_recurse failed at %s: %s\n"),
2188 core_addr_to_string (region_address),
2189 mach_error_string (kret));
2190 return res_length;
2193 inferior_debug
2194 (9, _("darwin_read_write_inferior: "
2195 "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
2196 core_addr_to_string (region_address),
2197 core_addr_to_string (region_start),
2198 core_addr_to_string (region_length));
2200 /* Check for holes in memory. */
2201 if (region_start > region_address)
2203 warning (_("No memory at %s (vs %s+0x%x). Nothing written"),
2204 core_addr_to_string (region_address),
2205 core_addr_to_string (region_start),
2206 (unsigned)region_length);
2207 return res_length;
2210 /* Adjust the length. */
2211 region_length -= (region_address - region_start);
2212 if (region_length > aligned_length)
2213 region_length = aligned_length;
2215 /* Make the pages RW. */
2216 if (!(info.protection & VM_PROT_WRITE))
2218 vm_prot_t prot = VM_PROT_READ | VM_PROT_WRITE;
2220 kret = mach_vm_protect (task, region_address, region_length,
2221 FALSE, prot);
2222 if (kret != KERN_SUCCESS)
2224 prot |= VM_PROT_COPY;
2225 kret = mach_vm_protect (task, region_address, region_length,
2226 FALSE, prot);
2228 if (kret != KERN_SUCCESS)
2230 warning (_("darwin_read_write_inferior: "
2231 "mach_vm_protect failed at %s "
2232 "(len=0x%lx, prot=0x%x): %s"),
2233 core_addr_to_string (region_address),
2234 (unsigned long) region_length, (unsigned) prot,
2235 mach_error_string (kret));
2236 return res_length;
2240 if (offset + length > region_length)
2241 write_length = region_length - offset;
2242 else
2243 write_length = length;
2245 /* Write. */
2246 kret = mach_vm_write (task, addr, (vm_offset_t) wraddr, write_length);
2247 if (kret != KERN_SUCCESS)
2249 warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
2250 mach_error_string (kret));
2251 return res_length;
2254 /* Restore page rights. */
2255 if (!(info.protection & VM_PROT_WRITE))
2257 kret = mach_vm_protect (task, region_address, region_length,
2258 FALSE, info.protection);
2259 if (kret != KERN_SUCCESS)
2261 warning (_("darwin_read_write_inferior: "
2262 "mach_vm_protect restore failed at %s "
2263 "(len=0x%lx): %s"),
2264 core_addr_to_string (region_address),
2265 (unsigned long) region_length,
2266 mach_error_string (kret));
2270 addr += write_length;
2271 wraddr += write_length;
2272 res_length += write_length;
2273 length -= write_length;
2276 return res_length;
2279 /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
2280 to RDADDR (in big endian).
2281 Return 0 on failure; number of bytes read / written otherwise. */
2283 #ifdef TASK_DYLD_INFO_COUNT
2284 /* This is not available in Darwin 9. */
2285 static enum target_xfer_status
2286 darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
2287 ULONGEST length, ULONGEST *xfered_len)
2289 struct task_dyld_info task_dyld_info;
2290 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
2291 kern_return_t kret;
2293 if (addr != 0 || length > sizeof (mach_vm_address_t))
2294 return TARGET_XFER_EOF;
2296 kret = task_info (task, TASK_DYLD_INFO,
2297 (task_info_t) &task_dyld_info, &count);
2298 MACH_CHECK_ERROR (kret);
2299 if (kret != KERN_SUCCESS)
2300 return TARGET_XFER_E_IO;
2302 store_unsigned_integer (rdaddr, length, BFD_ENDIAN_BIG,
2303 task_dyld_info.all_image_info_addr);
2304 *xfered_len = (ULONGEST) length;
2305 return TARGET_XFER_OK;
2307 #endif
2311 enum target_xfer_status
2312 darwin_nat_target::xfer_partial (enum target_object object, const char *annex,
2313 gdb_byte *readbuf, const gdb_byte *writebuf,
2314 ULONGEST offset, ULONGEST len,
2315 ULONGEST *xfered_len)
2317 struct inferior *inf = current_inferior ();
2318 darwin_inferior *priv = get_darwin_inferior (inf);
2320 inferior_debug
2321 (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
2322 core_addr_to_string (offset), pulongest (len),
2323 host_address_to_string (readbuf), host_address_to_string (writebuf),
2324 inf->pid);
2326 switch (object)
2328 case TARGET_OBJECT_MEMORY:
2330 int l = darwin_read_write_inferior (priv->task, offset,
2331 readbuf, writebuf, len);
2333 if (l == 0)
2334 return TARGET_XFER_EOF;
2335 else
2337 gdb_assert (l > 0);
2338 *xfered_len = (ULONGEST) l;
2339 return TARGET_XFER_OK;
2342 #ifdef TASK_DYLD_INFO_COUNT
2343 case TARGET_OBJECT_DARWIN_DYLD_INFO:
2344 if (writebuf != NULL || readbuf == NULL)
2346 /* Support only read. */
2347 return TARGET_XFER_E_IO;
2349 return darwin_read_dyld_info (priv->task, offset, readbuf, len,
2350 xfered_len);
2351 #endif
2352 default:
2353 return TARGET_XFER_E_IO;
2358 static void
2359 set_enable_mach_exceptions (const char *args, int from_tty,
2360 struct cmd_list_element *c)
2362 if (inferior_ptid != null_ptid)
2364 struct inferior *inf = current_inferior ();
2365 darwin_inferior *priv = get_darwin_inferior (inf);
2366 exception_mask_t mask;
2367 kern_return_t kret;
2369 if (enable_mach_exceptions)
2370 mask = EXC_MASK_ALL;
2371 else
2373 darwin_restore_exception_ports (priv);
2374 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
2376 kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
2377 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
2378 MACH_CHECK_ERROR (kret);
2382 const char *
2383 darwin_nat_target::pid_to_exec_file (int pid)
2385 static char path[PATH_MAX];
2386 int res;
2388 res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
2389 if (res >= 0)
2390 return path;
2391 else
2392 return NULL;
2395 ptid_t
2396 darwin_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
2398 struct inferior *inf = current_inferior ();
2399 darwin_inferior *priv = get_darwin_inferior (inf);
2400 kern_return_t kret;
2401 mach_port_name_array_t names;
2402 mach_msg_type_number_t names_count;
2403 mach_port_type_array_t types;
2404 mach_msg_type_number_t types_count;
2405 long res = 0;
2407 /* First linear search. */
2408 for (darwin_thread_t *t : priv->threads)
2410 if (t->inf_port == lwp)
2411 return ptid_t (inferior_ptid.pid (), 0, t->gdb_port);
2414 /* Maybe the port was never extract. Do it now. */
2416 /* First get inferior port names. */
2417 kret = mach_port_names (priv->task, &names, &names_count, &types,
2418 &types_count);
2419 MACH_CHECK_ERROR (kret);
2420 if (kret != KERN_SUCCESS)
2421 return null_ptid;
2423 /* For each name, copy the right in the gdb space and then compare with
2424 our view of the inferior threads. We don't forget to deallocate the
2425 right. */
2426 for (int i = 0; i < names_count; i++)
2428 mach_port_t local_name;
2429 mach_msg_type_name_t local_type;
2431 /* We just need to know the corresponding name in gdb name space.
2432 So extract and deallocate the right. */
2433 kret = mach_port_extract_right (priv->task, names[i],
2434 MACH_MSG_TYPE_COPY_SEND,
2435 &local_name, &local_type);
2436 if (kret != KERN_SUCCESS)
2437 continue;
2438 mach_port_deallocate (gdb_task, local_name);
2440 for (darwin_thread_t *t : priv->threads)
2442 if (t->gdb_port == local_name)
2444 t->inf_port = names[i];
2445 if (names[i] == lwp)
2446 res = t->gdb_port;
2451 vm_deallocate (gdb_task, (vm_address_t) names,
2452 names_count * sizeof (mach_port_t));
2454 if (res)
2455 return ptid_t (current_inferior ()->pid, 0, res);
2456 else
2457 return null_ptid;
2460 bool
2461 darwin_nat_target::supports_multi_process ()
2463 return true;
2466 void _initialize_darwin_nat ();
2467 void
2468 _initialize_darwin_nat ()
2470 kern_return_t kret;
2472 gdb_task = mach_task_self ();
2473 darwin_host_self = mach_host_self ();
2475 /* Read page size. */
2476 kret = host_page_size (darwin_host_self, &mach_page_size);
2477 if (kret != KERN_SUCCESS)
2479 mach_page_size = 0x1000;
2480 MACH_CHECK_ERROR (kret);
2483 inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"),
2484 (unsigned long) mach_task_self (), getpid ());
2486 add_setshow_zuinteger_cmd ("darwin", class_obscure,
2487 &darwin_debug_flag, _("\
2488 Set if printing inferior communication debugging statements."), _("\
2489 Show if printing inferior communication debugging statements."), NULL,
2490 NULL, NULL,
2491 &setdebuglist, &showdebuglist);
2493 add_setshow_boolean_cmd ("mach-exceptions", class_support,
2494 &enable_mach_exceptions, _("\
2495 Set if mach exceptions are caught."), _("\
2496 Show if mach exceptions are caught."), _("\
2497 When this mode is on, all low level exceptions are reported before being\n\
2498 reported by the kernel."),
2499 &set_enable_mach_exceptions, NULL,
2500 &setlist, &showlist);