Add translations for various sub-directories
[binutils-gdb.git] / gdb / darwin-nat.c
blobe1ea020bd5c1e5a5fe3e825785453b1574cf0195
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"
73 #include "gdbsupport/eintr.h"
75 /* Quick overview.
76 Darwin kernel is Mach + BSD derived kernel. Note that they share the
77 same memory space and are linked together (ie there is no micro-kernel).
79 Although ptrace(2) is available on Darwin, it is not complete. We have
80 to use Mach calls to read and write memory and to modify registers. We
81 also use Mach to get inferior faults. As we cannot use select(2) or
82 signals with Mach port (the Mach communication channel), signals are
83 reported to gdb as an exception. Furthermore we detect death of the
84 inferior through a Mach notification message. This way we only wait
85 on Mach ports.
87 Some Mach documentation is available for Apple xnu source package or
88 from the web. */
91 #define PTRACE(CMD, PID, ADDR, SIG) \
92 darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
94 static void darwin_ptrace_me (void);
96 static void darwin_encode_reply (mig_reply_error_t *reply,
97 mach_msg_header_t *hdr, integer_t code);
99 static void darwin_setup_request_notification (struct inferior *inf);
100 static void darwin_deallocate_exception_ports (darwin_inferior *inf);
101 static void darwin_setup_exceptions (struct inferior *inf);
102 static void darwin_deallocate_threads (struct inferior *inf);
104 /* Task identifier of gdb. */
105 static task_t gdb_task;
107 /* A copy of mach_host_self (). */
108 mach_port_t darwin_host_self;
110 /* Exception port. */
111 mach_port_t darwin_ex_port;
113 /* Port set, to wait for answer on all ports. */
114 mach_port_t darwin_port_set;
116 /* Page size. */
117 static vm_size_t mach_page_size;
119 /* If Set, catch all mach exceptions (before they are converted to signals
120 by the kernel). */
121 static bool enable_mach_exceptions;
123 /* Inferior that should report a fake stop event. */
124 static struct inferior *darwin_inf_fake_stop;
126 /* If non-NULL, the shell we actually invoke. See maybe_cache_shell
127 for details. */
128 static const char *copied_shell;
130 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
131 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
133 /* This controls output of inferior debugging. */
134 static unsigned int darwin_debug_flag = 0;
136 /* Create a __TEXT __info_plist section in the executable so that gdb could
137 be signed. This is required to get an authorization for task_for_pid.
139 Once gdb is built, you must codesign it with any system-trusted signing
140 authority. See taskgated(8) for details. */
141 static const unsigned char info_plist[]
142 __attribute__ ((section ("__TEXT,__info_plist"),used)) =
143 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
144 "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
145 " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
146 "<plist version=\"1.0\">\n"
147 "<dict>\n"
148 " <key>CFBundleIdentifier</key>\n"
149 " <string>org.gnu.gdb</string>\n"
150 " <key>CFBundleName</key>\n"
151 " <string>gdb</string>\n"
152 " <key>CFBundleVersion</key>\n"
153 " <string>1.0</string>\n"
154 " <key>SecTaskAccess</key>\n"
155 " <array>\n"
156 " <string>allowed</string>\n"
157 " <string>debug</string>\n"
158 " </array>\n"
159 "</dict>\n"
160 "</plist>\n";
162 static void inferior_debug (int level, const char *fmt, ...)
163 ATTRIBUTE_PRINTF (2, 3);
165 static void
166 inferior_debug (int level, const char *fmt, ...)
168 va_list ap;
170 if (darwin_debug_flag < level)
171 return;
173 va_start (ap, fmt);
174 gdb_printf (gdb_stdlog, _("[%d inferior]: "), getpid ());
175 gdb_vprintf (gdb_stdlog, fmt, ap);
176 va_end (ap);
179 void
180 mach_check_error (kern_return_t ret, const char *file,
181 unsigned int line, const char *func)
183 if (ret == KERN_SUCCESS)
184 return;
185 if (func == NULL)
186 func = _("[UNKNOWN]");
188 warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
189 file, line, func, mach_error_string (ret), (unsigned long) ret);
192 static const char *
193 unparse_exception_type (unsigned int i)
195 static char unknown_exception_buf[32];
197 switch (i)
199 case EXC_BAD_ACCESS:
200 return "EXC_BAD_ACCESS";
201 case EXC_BAD_INSTRUCTION:
202 return "EXC_BAD_INSTRUCTION";
203 case EXC_ARITHMETIC:
204 return "EXC_ARITHMETIC";
205 case EXC_EMULATION:
206 return "EXC_EMULATION";
207 case EXC_SOFTWARE:
208 return "EXC_SOFTWARE";
209 case EXC_BREAKPOINT:
210 return "EXC_BREAKPOINT";
211 case EXC_SYSCALL:
212 return "EXC_SYSCALL";
213 case EXC_MACH_SYSCALL:
214 return "EXC_MACH_SYSCALL";
215 case EXC_RPC_ALERT:
216 return "EXC_RPC_ALERT";
217 case EXC_CRASH:
218 return "EXC_CRASH";
219 default:
220 snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
221 return unknown_exception_buf;
225 /* Set errno to zero, and then call ptrace with the given arguments.
226 If inferior debugging traces are on, then also print a debug
227 trace.
229 The returned value is the same as the value returned by ptrace,
230 except in the case where that value is -1 but errno is zero.
231 This case is documented to be a non-error situation, so we
232 return zero in that case. */
234 static int
235 darwin_ptrace (const char *name,
236 int request, int pid, caddr_t arg3, int arg4)
238 int ret;
240 errno = 0;
241 ret = ptrace (request, pid, arg3, arg4);
242 if (ret == -1 && errno == 0)
243 ret = 0;
245 inferior_debug (4, _("ptrace (%s, %d, 0x%lx, %d): %d (%s)\n"),
246 name, pid, (unsigned long) arg3, arg4, ret,
247 (ret != 0) ? safe_strerror (errno) : _("no error"));
248 return ret;
251 static int
252 cmp_thread_t (const void *l, const void *r)
254 thread_t tl = *(const thread_t *)l;
255 thread_t tr = *(const thread_t *)r;
256 return (int)(tl - tr);
259 void
260 darwin_nat_target::check_new_threads (inferior *inf)
262 kern_return_t kret;
263 thread_array_t thread_list;
264 unsigned int new_nbr;
265 unsigned int old_nbr;
266 unsigned int new_ix, old_ix;
267 darwin_inferior *darwin_inf = get_darwin_inferior (inf);
268 std::vector<darwin_thread_t *> new_thread_vec;
270 if (darwin_inf == nullptr)
271 return;
273 /* Get list of threads. */
274 kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
275 MACH_CHECK_ERROR (kret);
276 if (kret != KERN_SUCCESS)
277 return;
279 /* Sort the list. */
280 if (new_nbr > 1)
281 qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
283 old_nbr = darwin_inf->threads.size ();
285 /* Quick check for no changes. */
286 if (old_nbr == new_nbr)
288 size_t i;
290 for (i = 0; i < new_nbr; i++)
291 if (thread_list[i] != darwin_inf->threads[i]->gdb_port)
292 break;
293 if (i == new_nbr)
295 /* Deallocate ports. */
296 for (i = 0; i < new_nbr; i++)
298 kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
299 MACH_CHECK_ERROR (kret);
302 /* Deallocate the buffer. */
303 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
304 new_nbr * sizeof (int));
305 MACH_CHECK_ERROR (kret);
307 return;
311 /* Full handling: detect new threads, remove dead threads. */
313 new_thread_vec.reserve (new_nbr);
315 for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
317 thread_t new_id = (new_ix < new_nbr) ? thread_list[new_ix] : THREAD_NULL;
318 darwin_thread_t *old
319 = (old_ix < old_nbr) ? darwin_inf->threads[old_ix] : NULL;
320 thread_t old_id = old != NULL ? old->gdb_port : THREAD_NULL;
322 inferior_debug
323 (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
324 new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
326 if (old_id == new_id)
328 /* Thread still exist. */
329 new_thread_vec.push_back (old);
330 new_ix++;
331 old_ix++;
333 /* Deallocate the port. */
334 kret = mach_port_deallocate (gdb_task, new_id);
335 MACH_CHECK_ERROR (kret);
337 continue;
339 if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
341 /* Ignore dead ports.
342 In some weird cases, we might get dead ports. They should
343 correspond to dead thread so they could safely be ignored. */
344 new_ix++;
345 continue;
347 if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
349 /* A thread was created. */
350 darwin_thread_info *pti = new darwin_thread_info;
352 pti->gdb_port = new_id;
353 pti->msg_state = DARWIN_RUNNING;
355 /* Add the new thread. */
356 add_thread_with_info (this, ptid_t (inf->pid, 0, new_id),
357 private_thread_info_up (pti));
358 new_thread_vec.push_back (pti);
359 new_ix++;
360 continue;
362 if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
364 /* A thread was removed. */
365 struct thread_info *thr
366 = this->find_thread (ptid_t (inf->pid, 0, old_id));
367 delete_thread (thr);
368 kret = mach_port_deallocate (gdb_task, old_id);
369 MACH_CHECK_ERROR (kret);
370 old_ix++;
371 continue;
373 gdb_assert_not_reached ("unexpected thread case");
376 darwin_inf->threads = std::move (new_thread_vec);
378 /* Deallocate the buffer. */
379 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
380 new_nbr * sizeof (int));
381 MACH_CHECK_ERROR (kret);
384 /* Return an inferior by task port. */
385 static struct inferior *
386 darwin_find_inferior_by_task (task_t port)
388 for (inferior *inf : all_inferiors ())
390 darwin_inferior *priv = get_darwin_inferior (inf);
392 if (priv != nullptr && priv->task == port)
393 return inf;
395 return nullptr;
398 /* Return an inferior by pid port. */
399 static struct inferior *
400 darwin_find_inferior_by_pid (int pid)
402 for (inferior *inf : all_inferiors ())
404 if (inf->pid == pid)
405 return inf;
407 return nullptr;
410 /* Return a thread by port. */
411 static darwin_thread_t *
412 darwin_find_thread (struct inferior *inf, thread_t thread)
414 darwin_inferior *priv = get_darwin_inferior (inf);
416 if (priv != nullptr)
417 for (darwin_thread_t *t : priv->threads)
419 if (t->gdb_port == thread)
420 return t;
423 return NULL;
426 /* Suspend (ie stop) an inferior at Mach level. */
428 static void
429 darwin_suspend_inferior (struct inferior *inf)
431 darwin_inferior *priv = get_darwin_inferior (inf);
433 if (priv != nullptr && !priv->suspended)
435 kern_return_t kret;
437 kret = task_suspend (priv->task);
438 MACH_CHECK_ERROR (kret);
440 priv->suspended = 1;
444 /* Resume an inferior at Mach level. */
446 static void
447 darwin_resume_inferior (struct inferior *inf)
449 darwin_inferior *priv = get_darwin_inferior (inf);
451 if (priv != nullptr && priv->suspended)
453 kern_return_t kret;
455 kret = task_resume (priv->task);
456 MACH_CHECK_ERROR (kret);
458 priv->suspended = 0;
462 static void
463 darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
465 gdb_printf (gdb_stdlog,
466 _("message header:\n"));
467 gdb_printf (gdb_stdlog,
468 _(" bits: 0x%x\n"), hdr->msgh_bits);
469 gdb_printf (gdb_stdlog,
470 _(" size: 0x%x\n"), hdr->msgh_size);
471 gdb_printf (gdb_stdlog,
472 _(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
473 gdb_printf (gdb_stdlog,
474 _(" local-port: 0x%x\n"), hdr->msgh_local_port);
475 gdb_printf (gdb_stdlog,
476 _(" reserved: 0x%x\n"), hdr->msgh_reserved);
477 gdb_printf (gdb_stdlog,
478 _(" id: 0x%x\n"), hdr->msgh_id);
480 if (disp_body)
482 const unsigned char *data;
483 const unsigned int *ldata;
484 int size;
485 int i;
487 data = (unsigned char *)(hdr + 1);
488 size = hdr->msgh_size - sizeof (mach_msg_header_t);
490 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
492 mach_msg_body_t *bod = (mach_msg_body_t*)data;
493 mach_msg_port_descriptor_t *desc =
494 (mach_msg_port_descriptor_t *)(bod + 1);
495 int k;
496 NDR_record_t *ndr;
497 gdb_printf (gdb_stdlog,
498 _("body: descriptor_count=%u\n"),
499 bod->msgh_descriptor_count);
500 data += sizeof (mach_msg_body_t);
501 size -= sizeof (mach_msg_body_t);
502 for (k = 0; k < bod->msgh_descriptor_count; k++)
503 switch (desc[k].type)
505 case MACH_MSG_PORT_DESCRIPTOR:
506 gdb_printf
507 (gdb_stdlog,
508 _(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
509 k, desc[k].type, desc[k].name, desc[k].disposition);
510 break;
511 default:
512 gdb_printf (gdb_stdlog,
513 _(" descr %d: type=%u\n"),
514 k, desc[k].type);
515 break;
517 data += bod->msgh_descriptor_count
518 * sizeof (mach_msg_port_descriptor_t);
519 size -= bod->msgh_descriptor_count
520 * sizeof (mach_msg_port_descriptor_t);
521 ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
522 gdb_printf
523 (gdb_stdlog,
524 _("NDR: mig=%02x if=%02x encod=%02x "
525 "int=%02x char=%02x float=%02x\n"),
526 ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
527 ndr->int_rep, ndr->char_rep, ndr->float_rep);
528 data += sizeof (NDR_record_t);
529 size -= sizeof (NDR_record_t);
532 gdb_printf (gdb_stdlog, _(" data:"));
533 ldata = (const unsigned int *)data;
534 for (i = 0; i < size / sizeof (unsigned int); i++)
535 gdb_printf (gdb_stdlog, " %08x", ldata[i]);
536 gdb_printf (gdb_stdlog, _("\n"));
540 /* Adjust inferior data when a new task was created. */
542 static struct inferior *
543 darwin_find_new_inferior (task_t task_port, thread_t thread_port)
545 int task_pid;
546 struct inferior *inf;
547 kern_return_t kret;
548 mach_port_t prev;
550 /* Find the corresponding pid. */
551 kret = pid_for_task (task_port, &task_pid);
552 if (kret != KERN_SUCCESS)
554 MACH_CHECK_ERROR (kret);
555 return NULL;
558 /* Find the inferior for this pid. */
559 inf = darwin_find_inferior_by_pid (task_pid);
560 if (inf == NULL)
561 return NULL;
563 darwin_inferior *priv = get_darwin_inferior (inf);
565 /* Deallocate saved exception ports. */
566 darwin_deallocate_exception_ports (priv);
568 /* No need to remove dead_name notification, but still... */
569 kret = mach_port_request_notification (gdb_task, priv->task,
570 MACH_NOTIFY_DEAD_NAME, 0,
571 MACH_PORT_NULL,
572 MACH_MSG_TYPE_MAKE_SEND_ONCE,
573 &prev);
574 if (kret != KERN_INVALID_ARGUMENT)
575 MACH_CHECK_ERROR (kret);
577 /* Replace old task port. */
578 kret = mach_port_deallocate (gdb_task, priv->task);
579 MACH_CHECK_ERROR (kret);
580 priv->task = task_port;
582 darwin_setup_request_notification (inf);
583 darwin_setup_exceptions (inf);
585 return inf;
588 /* Check data representation. */
590 static int
591 darwin_check_message_ndr (NDR_record_t *ndr)
593 if (ndr->mig_vers != NDR_PROTOCOL_2_0
594 || ndr->if_vers != NDR_PROTOCOL_2_0
595 || ndr->mig_encoding != NDR_record.mig_encoding
596 || ndr->int_rep != NDR_record.int_rep
597 || ndr->char_rep != NDR_record.char_rep
598 || ndr->float_rep != NDR_record.float_rep)
599 return -1;
600 return 0;
603 /* Decode an exception message. */
606 darwin_nat_target::decode_exception_message (mach_msg_header_t *hdr,
607 inferior **pinf,
608 darwin_thread_t **pthread)
610 mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
611 mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
612 NDR_record_t *ndr;
613 integer_t *data;
614 struct inferior *inf;
615 darwin_thread_t *thread;
616 task_t task_port;
617 thread_t thread_port;
618 kern_return_t kret;
619 int i;
621 /* Check message destination. */
622 if (hdr->msgh_local_port != darwin_ex_port)
623 return -1;
625 /* Check message header. */
626 if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
627 return -1;
629 /* Check descriptors. */
630 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
631 + sizeof (*ndr) + 2 * sizeof (integer_t))
632 || bod->msgh_descriptor_count != 2
633 || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
634 || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
635 || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
636 || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
637 return -1;
639 /* Check data representation. */
640 ndr = (NDR_record_t *)(desc + 2);
641 if (darwin_check_message_ndr (ndr) != 0)
642 return -1;
644 /* Ok, the hard work. */
645 data = (integer_t *)(ndr + 1);
647 task_port = desc[1].name;
648 thread_port = desc[0].name;
650 /* Find process by port. */
651 inf = darwin_find_inferior_by_task (task_port);
652 *pinf = inf;
654 if (inf == NULL && data[0] == EXC_SOFTWARE && data[1] == 2
655 && data[2] == EXC_SOFT_SIGNAL && data[3] == SIGTRAP)
657 /* Not a known inferior, but a sigtrap. This happens on darwin 16.1.0,
658 as a new Mach task is created when a process exec. */
659 inf = darwin_find_new_inferior (task_port, thread_port);
660 *pinf = inf;
662 if (inf == NULL)
664 /* Deallocate task_port, unless it was saved. */
665 kret = mach_port_deallocate (mach_task_self (), task_port);
666 MACH_CHECK_ERROR (kret);
669 else
671 /* We got new rights to the task, get rid of it. Do not get rid of
672 thread right, as we will need it to find the thread. */
673 kret = mach_port_deallocate (mach_task_self (), task_port);
674 MACH_CHECK_ERROR (kret);
677 if (inf == NULL)
679 /* Not a known inferior. This could happen if the child fork, as
680 the created process will inherit its exception port.
681 FIXME: should the exception port be restored ? */
682 mig_reply_error_t reply;
684 inferior_debug
685 (4, _("darwin_decode_exception_message: unknown task 0x%x\n"),
686 task_port);
688 /* Free thread port (we don't know it). */
689 kret = mach_port_deallocate (mach_task_self (), thread_port);
690 MACH_CHECK_ERROR (kret);
692 darwin_encode_reply (&reply, hdr, KERN_SUCCESS);
694 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
695 reply.Head.msgh_size, 0,
696 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
697 MACH_PORT_NULL);
698 MACH_CHECK_ERROR (kret);
700 return 0;
703 /* Find thread by port. */
704 /* Check for new threads. Do it early so that the port in the exception
705 message can be deallocated. */
706 check_new_threads (inf);
708 /* Free the thread port (as gdb knows the thread, it has already has a right
709 for it, so this just decrement a reference counter). */
710 kret = mach_port_deallocate (mach_task_self (), thread_port);
711 MACH_CHECK_ERROR (kret);
713 thread = darwin_find_thread (inf, thread_port);
714 if (thread == NULL)
715 return -1;
716 *pthread = thread;
718 /* The thread should be running. However we have observed cases where a
719 thread got a SIGTTIN message after being stopped. */
720 gdb_assert (thread->msg_state != DARWIN_MESSAGE);
722 /* Finish decoding. */
723 thread->event.header = *hdr;
724 thread->event.thread_port = thread_port;
725 thread->event.task_port = task_port;
726 thread->event.ex_type = data[0];
727 thread->event.data_count = data[1];
729 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
730 + sizeof (*ndr) + 2 * sizeof (integer_t)
731 + data[1] * sizeof (integer_t)))
732 return -1;
733 for (i = 0; i < data[1]; i++)
734 thread->event.ex_data[i] = data[2 + i];
736 thread->msg_state = DARWIN_MESSAGE;
738 return 0;
741 /* Decode dead_name notify message. */
743 static int
744 darwin_decode_notify_message (mach_msg_header_t *hdr, struct inferior **pinf)
746 NDR_record_t *ndr = (NDR_record_t *)(hdr + 1);
747 integer_t *data = (integer_t *)(ndr + 1);
748 struct inferior *inf;
749 task_t task_port;
751 /* Check message header. */
752 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
753 return -1;
755 /* Check descriptors. */
756 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*ndr) + sizeof (integer_t)))
757 return -2;
759 /* Check data representation. */
760 if (darwin_check_message_ndr (ndr) != 0)
761 return -3;
763 task_port = data[0];
765 /* Find process by port. */
766 inf = darwin_find_inferior_by_task (task_port);
767 *pinf = inf;
769 /* Check message destination. */
770 if (inf != NULL)
772 darwin_inferior *priv = get_darwin_inferior (inf);
773 if (hdr->msgh_local_port != priv->notify_port)
774 return -4;
777 return 0;
780 static void
781 darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
782 integer_t code)
784 mach_msg_header_t *rh = &reply->Head;
786 rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
787 rh->msgh_remote_port = hdr->msgh_remote_port;
788 rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
789 rh->msgh_local_port = MACH_PORT_NULL;
790 rh->msgh_id = hdr->msgh_id + 100;
792 reply->NDR = NDR_record;
793 reply->RetCode = code;
796 static void
797 darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
799 kern_return_t kret;
800 mig_reply_error_t reply;
801 darwin_inferior *priv = get_darwin_inferior (inf);
803 darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
805 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
806 reply.Head.msgh_size, 0,
807 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
808 MACH_PORT_NULL);
809 MACH_CHECK_ERROR (kret);
811 priv->pending_messages--;
814 /* Wrapper around the __pthread_kill syscall. We use this instead of the
815 pthread_kill function to be able to send a signal to any kind of thread,
816 including GCD threads. */
818 static int
819 darwin_pthread_kill (darwin_thread_t *thread, int nsignal)
821 DIAGNOSTIC_PUSH;
822 DIAGNOSTIC_IGNORE_DEPRECATED_DECLARATIONS;
823 int res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
824 DIAGNOSTIC_POP;
825 return res;
828 static void
829 darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
830 int step, int nsignal)
832 inferior_debug
833 (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
834 thread->msg_state, thread->gdb_port, step, nsignal);
836 switch (thread->msg_state)
838 case DARWIN_MESSAGE:
839 if (thread->event.ex_type == EXC_SOFTWARE
840 && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
842 /* Either deliver a new signal or cancel the signal received. */
843 int res = PTRACE (PT_THUPDATE, inf->pid,
844 (caddr_t) (uintptr_t) thread->gdb_port, nsignal);
845 if (res < 0)
846 inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
848 else if (nsignal)
850 /* Note: ptrace is allowed only if the process is stopped.
851 Directly send the signal to the thread. */
852 int res = darwin_pthread_kill (thread, nsignal);
853 inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
854 thread->gdb_port, nsignal, res);
855 thread->signaled = 1;
858 /* Set or reset single step. */
859 inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
860 thread->gdb_port, step);
861 darwin_set_sstep (thread->gdb_port, step);
862 thread->single_step = step;
864 darwin_send_reply (inf, thread);
865 thread->msg_state = DARWIN_RUNNING;
866 break;
868 case DARWIN_RUNNING:
869 break;
871 case DARWIN_STOPPED:
872 kern_return_t kret = thread_resume (thread->gdb_port);
873 MACH_CHECK_ERROR (kret);
875 thread->msg_state = DARWIN_RUNNING;
876 break;
880 /* Resume all threads of the inferior. */
882 static void
883 darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
885 darwin_inferior *priv = get_darwin_inferior (inf);
887 if (priv != nullptr)
888 for (darwin_thread_t *thread : priv->threads)
889 darwin_resume_thread (inf, thread, step, nsignal);
892 /* Suspend all threads of INF. */
894 static void
895 darwin_suspend_inferior_threads (struct inferior *inf)
897 darwin_inferior *priv = get_darwin_inferior (inf);
899 for (darwin_thread_t *thread : priv->threads)
901 switch (thread->msg_state)
903 case DARWIN_STOPPED:
904 case DARWIN_MESSAGE:
905 break;
906 case DARWIN_RUNNING:
908 kern_return_t kret = thread_suspend (thread->gdb_port);
909 MACH_CHECK_ERROR (kret);
910 thread->msg_state = DARWIN_STOPPED;
911 break;
917 void
918 darwin_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signal)
920 int nsignal;
922 inferior_debug
923 (2, _("darwin_resume: ptid=%s, step=%d, signal=%d\n"),
924 ptid.to_string ().c_str (), step, signal);
926 if (signal == GDB_SIGNAL_0)
927 nsignal = 0;
928 else
929 nsignal = gdb_signal_to_host (signal);
931 /* Don't try to single step all threads. */
932 if (step)
933 ptid = inferior_ptid;
935 /* minus_one_ptid is RESUME_ALL. */
936 if (ptid == minus_one_ptid)
938 /* Resume threads. */
939 for (inferior *inf : all_inferiors ())
940 darwin_resume_inferior_threads (inf, step, nsignal);
942 /* Resume tasks. */
943 for (inferior *inf : all_inferiors ())
944 darwin_resume_inferior (inf);
946 else
948 inferior *inf = find_inferior_ptid (this, ptid);
949 long tid = ptid.tid ();
951 /* Stop the inferior (should be useless). */
952 darwin_suspend_inferior (inf);
954 if (tid == 0)
955 darwin_resume_inferior_threads (inf, step, nsignal);
956 else
958 darwin_thread_t *thread;
960 /* Suspend threads of the task. */
961 darwin_suspend_inferior_threads (inf);
963 /* Resume the selected thread. */
964 thread = darwin_find_thread (inf, tid);
965 gdb_assert (thread);
966 darwin_resume_thread (inf, thread, step, nsignal);
969 /* Resume the task. */
970 darwin_resume_inferior (inf);
974 ptid_t
975 darwin_nat_target::decode_message (mach_msg_header_t *hdr,
976 darwin_thread_t **pthread,
977 inferior **pinf,
978 target_waitstatus *status)
980 darwin_thread_t *thread;
981 struct inferior *inf;
983 /* Exception message. 2401 == 0x961 is exc. */
984 if (hdr->msgh_id == 2401)
986 int res;
988 /* Decode message. */
989 res = decode_exception_message (hdr, &inf, &thread);
991 if (res < 0)
993 /* Should not happen... */
994 warning (_("darwin_wait: ill-formatted message (id=0x%x)\n"),
995 hdr->msgh_id);
996 /* FIXME: send a failure reply? */
997 status->set_ignore ();
998 return minus_one_ptid;
1000 if (inf == NULL)
1002 status->set_ignore ();
1003 return minus_one_ptid;
1005 *pinf = inf;
1006 *pthread = thread;
1008 darwin_inferior *priv = get_darwin_inferior (inf);
1010 priv->pending_messages++;
1012 thread->msg_state = DARWIN_MESSAGE;
1014 inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
1015 thread->gdb_port,
1016 unparse_exception_type (thread->event.ex_type));
1018 switch (thread->event.ex_type)
1020 case EXC_BAD_ACCESS:
1021 status->set_stopped (GDB_EXC_BAD_ACCESS);
1022 break;
1023 case EXC_BAD_INSTRUCTION:
1024 status->set_stopped (GDB_EXC_BAD_INSTRUCTION);
1025 break;
1026 case EXC_ARITHMETIC:
1027 status->set_stopped (GDB_EXC_ARITHMETIC);
1028 break;
1029 case EXC_EMULATION:
1030 status->set_stopped (GDB_EXC_EMULATION);
1031 break;
1032 case EXC_SOFTWARE:
1033 if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
1035 status->set_stopped
1036 (gdb_signal_from_host (thread->event.ex_data[1]));
1037 inferior_debug (5, _(" (signal %d: %s)\n"),
1038 thread->event.ex_data[1],
1039 gdb_signal_to_name (status->sig ()));
1041 /* If the thread is stopped because it has received a signal
1042 that gdb has just sent, continue. */
1043 if (thread->signaled)
1045 thread->signaled = 0;
1046 darwin_send_reply (inf, thread);
1047 thread->msg_state = DARWIN_RUNNING;
1048 status->set_ignore ();
1051 else
1052 status->set_stopped (GDB_EXC_SOFTWARE);
1053 break;
1054 case EXC_BREAKPOINT:
1055 /* Many internal GDB routines expect breakpoints to be reported
1056 as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
1057 as a spurious signal. */
1058 status->set_stopped (GDB_SIGNAL_TRAP);
1059 break;
1060 default:
1061 status->set_stopped (GDB_SIGNAL_UNKNOWN);
1062 break;
1065 return ptid_t (inf->pid, 0, thread->gdb_port);
1067 else if (hdr->msgh_id == 0x48)
1069 /* MACH_NOTIFY_DEAD_NAME: notification for exit *or* WIFSTOPPED. */
1070 int res;
1072 res = darwin_decode_notify_message (hdr, &inf);
1074 if (res < 0)
1076 /* Should not happen... */
1077 warning
1078 (_("darwin_wait: ill-formatted message (id=0x%x, res=%d)\n"),
1079 hdr->msgh_id, res);
1082 *pinf = NULL;
1083 *pthread = NULL;
1085 if (res < 0 || inf == NULL)
1087 status->set_ignore ();
1088 return minus_one_ptid;
1091 if (inf != NULL)
1093 darwin_inferior *priv = get_darwin_inferior (inf);
1095 if (!priv->no_ptrace)
1097 pid_t res_pid;
1098 int wstatus;
1100 res_pid = wait4 (inf->pid, &wstatus, 0, NULL);
1101 if (res_pid < 0 || res_pid != inf->pid)
1103 warning (_("wait4: res=%d: %s\n"),
1104 res_pid, safe_strerror (errno));
1105 status->set_ignore ();
1106 return minus_one_ptid;
1108 if (WIFEXITED (wstatus))
1110 status->set_exited (WEXITSTATUS (wstatus));
1111 inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
1112 res_pid, wstatus);
1114 else if (WIFSTOPPED (wstatus))
1116 /* Ignore stopped state, it will be handled by the next
1117 exception. */
1118 status->set_ignore ();
1119 inferior_debug (4, _("darwin_wait: pid %d received WIFSTOPPED\n"),
1120 res_pid);
1121 return minus_one_ptid;
1123 else if (WIFSIGNALED (wstatus))
1125 status->set_signalled
1126 (gdb_signal_from_host (WTERMSIG (wstatus)));
1127 inferior_debug (4, _("darwin_wait: pid=%d received signal %d\n"),
1128 res_pid, status->sig());
1130 else
1132 status->set_ignore ();
1133 warning (_("Unexpected wait status after MACH_NOTIFY_DEAD_NAME "
1134 "notification: 0x%x"), wstatus);
1135 return minus_one_ptid;
1138 return ptid_t (inf->pid);
1140 else
1142 inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
1143 status->set_exited (0 /* Don't know. */);
1144 return ptid_t (inf->pid, 0, 0);
1149 /* Unknown message. */
1150 warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
1151 status->set_ignore ();
1152 return minus_one_ptid;
1156 darwin_nat_target::cancel_breakpoint (inferior *inf, ptid_t ptid)
1158 /* Arrange for a breakpoint to be hit again later. We will handle
1159 the current event, eventually we will resume this thread, and this
1160 breakpoint will trap again.
1162 If we do not do this, then we run the risk that the user will
1163 delete or disable the breakpoint, but the thread will have already
1164 tripped on it. */
1166 struct regcache *regcache = get_thread_regcache (this, ptid);
1167 struct gdbarch *gdbarch = regcache->arch ();
1168 CORE_ADDR pc;
1170 pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
1171 if (breakpoint_inserted_here_p (inf->aspace.get (), pc))
1173 inferior_debug (4, "cancel_breakpoint for thread 0x%lx\n",
1174 (unsigned long) ptid.tid ());
1176 /* Back up the PC if necessary. */
1177 if (gdbarch_decr_pc_after_break (gdbarch))
1178 regcache_write_pc (regcache, pc);
1180 return 1;
1182 return 0;
1185 ptid_t
1186 darwin_nat_target::wait_1 (ptid_t ptid, struct target_waitstatus *status)
1188 kern_return_t kret;
1189 union
1191 mach_msg_header_t hdr;
1192 char data[0x100];
1193 } msgin;
1194 mach_msg_header_t *hdr = &msgin.hdr;
1195 ptid_t res;
1196 darwin_thread_t *thread;
1198 inferior_debug
1199 (2, _("darwin_wait: waiting for a message ptid=%s\n"),
1200 ptid.to_string ().c_str ());
1202 /* Handle fake stop events at first. */
1203 if (darwin_inf_fake_stop != NULL)
1205 inferior *inf = darwin_inf_fake_stop;
1206 darwin_inf_fake_stop = NULL;
1208 darwin_inferior *priv = get_darwin_inferior (inf);
1210 status->set_stopped (GDB_SIGNAL_TRAP);
1211 thread = priv->threads[0];
1212 thread->msg_state = DARWIN_STOPPED;
1213 return ptid_t (inf->pid, 0, thread->gdb_port);
1218 /* set_sigint_trap (); */
1220 /* Wait for a message. */
1221 kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1222 sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1224 /* clear_sigint_trap (); */
1226 if (kret == MACH_RCV_INTERRUPTED)
1228 status->set_ignore ();
1229 return minus_one_ptid;
1232 if (kret != MACH_MSG_SUCCESS)
1234 inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
1235 status->set_spurious ();
1236 return minus_one_ptid;
1239 /* Debug: display message. */
1240 if (darwin_debug_flag > 10)
1241 darwin_dump_message (hdr, darwin_debug_flag > 11);
1243 inferior *inf;
1244 res = decode_message (hdr, &thread, &inf, status);
1245 if (res == minus_one_ptid)
1246 continue;
1248 /* Early return in case an inferior has exited. */
1249 if (inf == NULL)
1250 return res;
1252 while (status->kind () == TARGET_WAITKIND_IGNORE);
1254 /* Stop all tasks. */
1255 for (inferior *inf : all_inferiors (this))
1257 darwin_suspend_inferior (inf);
1258 check_new_threads (inf);
1261 /* Read pending messages. */
1262 while (1)
1264 struct target_waitstatus status2;
1265 ptid_t ptid2;
1267 kret = mach_msg (&msgin.hdr,
1268 MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1269 sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1271 if (kret == MACH_RCV_TIMED_OUT)
1272 break;
1273 if (kret != MACH_MSG_SUCCESS)
1275 inferior_debug
1276 (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
1277 break;
1280 /* Debug: display message. */
1281 if (darwin_debug_flag > 10)
1282 darwin_dump_message (hdr, darwin_debug_flag > 11);
1284 inferior *inf;
1285 ptid2 = decode_message (hdr, &thread, &inf, &status2);
1287 if (inf != NULL && thread != NULL
1288 && thread->event.ex_type == EXC_BREAKPOINT)
1290 if (thread->single_step
1291 || cancel_breakpoint (inf,
1292 ptid_t (inf->pid, 0, thread->gdb_port)))
1294 gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1295 darwin_send_reply (inf, thread);
1296 thread->msg_state = DARWIN_RUNNING;
1298 else
1299 inferior_debug
1300 (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
1301 thread->gdb_port);
1303 else
1304 inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1306 return res;
1309 ptid_t
1310 darwin_nat_target::wait (ptid_t ptid, struct target_waitstatus *status,
1311 target_wait_flags options)
1313 return wait_1 (ptid, status);
1316 void
1317 darwin_nat_target::interrupt ()
1319 struct inferior *inf = current_inferior ();
1320 darwin_inferior *priv = get_darwin_inferior (inf);
1322 /* FIXME: handle in no_ptrace mode. */
1323 gdb_assert (!priv->no_ptrace);
1324 ::kill (inf->pid, SIGINT);
1327 /* Deallocate threads port and vector. */
1329 static void
1330 darwin_deallocate_threads (struct inferior *inf)
1332 darwin_inferior *priv = get_darwin_inferior (inf);
1334 for (darwin_thread_t *t : priv->threads)
1336 kern_return_t kret = mach_port_deallocate (gdb_task, t->gdb_port);
1337 MACH_CHECK_ERROR (kret);
1340 priv->threads.clear ();
1343 void
1344 darwin_nat_target::mourn_inferior ()
1346 struct inferior *inf = current_inferior ();
1347 darwin_inferior *priv = get_darwin_inferior (inf);
1348 kern_return_t kret;
1349 mach_port_t prev;
1351 /* Deallocate threads. */
1352 darwin_deallocate_threads (inf);
1354 /* Remove notify_port from darwin_port_set. */
1355 kret = mach_port_move_member (gdb_task,
1356 priv->notify_port, MACH_PORT_NULL);
1357 MACH_CHECK_ERROR (kret);
1359 /* Remove task port dead_name notification. */
1360 kret = mach_port_request_notification (gdb_task, priv->task,
1361 MACH_NOTIFY_DEAD_NAME, 0,
1362 MACH_PORT_NULL,
1363 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1364 &prev);
1365 /* This can fail if the task is dead. */
1366 inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
1367 priv->task, prev, priv->notify_port);
1369 if (kret == KERN_SUCCESS)
1371 kret = mach_port_deallocate (gdb_task, prev);
1372 MACH_CHECK_ERROR (kret);
1375 /* Destroy notify_port. */
1376 kret = mach_port_destroy (gdb_task, priv->notify_port);
1377 MACH_CHECK_ERROR (kret);
1379 /* Deallocate saved exception ports. */
1380 darwin_deallocate_exception_ports (priv);
1382 /* Deallocate task port. */
1383 kret = mach_port_deallocate (gdb_task, priv->task);
1384 MACH_CHECK_ERROR (kret);
1386 inf->priv = NULL;
1388 inf_child_target::mourn_inferior ();
1391 static void
1392 darwin_reply_to_all_pending_messages (struct inferior *inf)
1394 darwin_inferior *priv = get_darwin_inferior (inf);
1396 for (darwin_thread_t *t : priv->threads)
1398 if (t->msg_state == DARWIN_MESSAGE)
1399 darwin_resume_thread (inf, t, 0, 0);
1403 void
1404 darwin_nat_target::stop_inferior (inferior *inf)
1406 struct target_waitstatus wstatus;
1407 ptid_t ptid;
1408 int res;
1409 darwin_inferior *priv = get_darwin_inferior (inf);
1411 gdb_assert (inf != NULL);
1413 darwin_suspend_inferior (inf);
1415 darwin_reply_to_all_pending_messages (inf);
1417 if (priv->no_ptrace)
1418 return;
1420 res = ::kill (inf->pid, SIGSTOP);
1421 if (res != 0)
1422 warning (_("cannot kill: %s"), safe_strerror (errno));
1424 /* Wait until the process is really stopped. */
1425 while (1)
1427 ptid = wait_1 (ptid_t (inf->pid), &wstatus);
1428 if (wstatus.kind () == TARGET_WAITKIND_STOPPED
1429 && wstatus.sig () == GDB_SIGNAL_STOP)
1430 break;
1434 static kern_return_t
1435 darwin_save_exception_ports (darwin_inferior *inf)
1437 kern_return_t kret;
1439 inf->exception_info.count =
1440 sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1442 kret = task_get_exception_ports
1443 (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1444 &inf->exception_info.count, inf->exception_info.ports,
1445 inf->exception_info.behaviors, inf->exception_info.flavors);
1446 return kret;
1449 static kern_return_t
1450 darwin_restore_exception_ports (darwin_inferior *inf)
1452 int i;
1453 kern_return_t kret;
1455 for (i = 0; i < inf->exception_info.count; i++)
1457 kret = task_set_exception_ports
1458 (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1459 inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1460 if (kret != KERN_SUCCESS)
1461 return kret;
1464 return KERN_SUCCESS;
1467 /* Deallocate saved exception ports. */
1469 static void
1470 darwin_deallocate_exception_ports (darwin_inferior *inf)
1472 int i;
1473 kern_return_t kret;
1475 for (i = 0; i < inf->exception_info.count; i++)
1477 kret = mach_port_deallocate (gdb_task, inf->exception_info.ports[i]);
1478 MACH_CHECK_ERROR (kret);
1480 inf->exception_info.count = 0;
1483 static void
1484 darwin_setup_exceptions (struct inferior *inf)
1486 darwin_inferior *priv = get_darwin_inferior (inf);
1487 kern_return_t kret;
1488 exception_mask_t mask;
1490 kret = darwin_save_exception_ports (priv);
1491 if (kret != KERN_SUCCESS)
1492 error (_("Unable to save exception ports, task_get_exception_ports"
1493 "returned: %d"),
1494 kret);
1496 /* Set exception port. */
1497 if (enable_mach_exceptions)
1498 mask = EXC_MASK_ALL;
1499 else
1500 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1501 kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
1502 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1503 if (kret != KERN_SUCCESS)
1504 error (_("Unable to set exception ports, task_set_exception_ports"
1505 "returned: %d"),
1506 kret);
1509 void
1510 darwin_nat_target::kill ()
1512 struct inferior *inf = current_inferior ();
1513 darwin_inferior *priv = get_darwin_inferior (inf);
1514 struct target_waitstatus wstatus;
1515 ptid_t ptid;
1516 kern_return_t kret;
1517 int res;
1519 if (inferior_ptid == null_ptid)
1520 return;
1522 gdb_assert (inf != NULL);
1524 kret = darwin_restore_exception_ports (priv);
1525 MACH_CHECK_ERROR (kret);
1527 darwin_reply_to_all_pending_messages (inf);
1529 res = ::kill (inf->pid, 9);
1531 if (res == 0)
1533 /* On MacOS version Sierra, the darwin_restore_exception_ports call
1534 does not work as expected.
1535 When the kill function is called, the SIGKILL signal is received
1536 by gdb whereas it should have been received by the kernel since
1537 the exception ports have been restored.
1538 This behavior is not the expected one thus gdb does not reply to
1539 the received SIGKILL message. This situation leads to a "busy"
1540 resource from the kernel point of view and the inferior is never
1541 released, causing it to remain as a zombie process, even after
1542 GDB exits.
1543 To work around this, we mark all the threads of the inferior as
1544 signaled thus darwin_decode_message function knows that the kill
1545 signal was sent by gdb and will take the appropriate action
1546 (cancel signal and reply to the signal message). */
1547 for (darwin_thread_t *thread : priv->threads)
1548 thread->signaled = 1;
1550 darwin_resume_inferior (inf);
1552 ptid = wait_1 (ptid_t (inf->pid), &wstatus);
1554 else if (errno != ESRCH)
1555 warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
1556 inf->pid, safe_strerror (errno));
1558 target_mourn_inferior (ptid_t (inf->pid));
1561 static void
1562 darwin_setup_request_notification (struct inferior *inf)
1564 darwin_inferior *priv = get_darwin_inferior (inf);
1565 kern_return_t kret;
1566 mach_port_t prev_not;
1568 kret = mach_port_request_notification (gdb_task, priv->task,
1569 MACH_NOTIFY_DEAD_NAME, 0,
1570 priv->notify_port,
1571 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1572 &prev_not);
1573 if (kret != KERN_SUCCESS)
1574 error (_("Termination notification request failed, "
1575 "mach_port_request_notification\n"
1576 "returned: %d"),
1577 kret);
1578 if (prev_not != MACH_PORT_NULL)
1580 /* This is unexpected, as there should not be any previously
1581 registered notification request. But this is not a fatal
1582 issue, so just emit a warning. */
1583 warning (_("\
1584 A task termination request was registered before the debugger registered\n\
1585 its own. This is unexpected, but should otherwise not have any actual\n\
1586 impact on the debugging session."));
1590 static void
1591 darwin_attach_pid (struct inferior *inf)
1593 kern_return_t kret;
1595 darwin_inferior *priv = new darwin_inferior;
1596 inf->priv.reset (priv);
1600 kret = task_for_pid (gdb_task, inf->pid, &priv->task);
1601 if (kret != KERN_SUCCESS)
1603 int status;
1605 if (!inf->attach_flag)
1607 kill (inf->pid, 9);
1608 gdb::waitpid (inf->pid, &status, 0);
1611 error
1612 (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
1613 " (please check gdb is codesigned - see taskgated(8))"),
1614 inf->pid, mach_error_string (kret), (unsigned long) kret);
1617 inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1618 priv->task, inf->pid);
1620 if (darwin_ex_port == MACH_PORT_NULL)
1622 /* Create a port to get exceptions. */
1623 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1624 &darwin_ex_port);
1625 if (kret != KERN_SUCCESS)
1626 error (_("Unable to create exception port, mach_port_allocate "
1627 "returned: %d"),
1628 kret);
1630 kret = mach_port_insert_right (gdb_task, darwin_ex_port,
1631 darwin_ex_port,
1632 MACH_MSG_TYPE_MAKE_SEND);
1633 if (kret != KERN_SUCCESS)
1634 error (_("Unable to create exception port, mach_port_insert_right "
1635 "returned: %d"),
1636 kret);
1638 /* Create a port set and put ex_port in it. */
1639 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1640 &darwin_port_set);
1641 if (kret != KERN_SUCCESS)
1642 error (_("Unable to create port set, mach_port_allocate "
1643 "returned: %d"),
1644 kret);
1646 kret = mach_port_move_member (gdb_task, darwin_ex_port,
1647 darwin_port_set);
1648 if (kret != KERN_SUCCESS)
1649 error (_("Unable to move exception port into new port set, "
1650 "mach_port_move_member\n"
1651 "returned: %d"),
1652 kret);
1655 /* Create a port to be notified when the child task terminates. */
1656 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1657 &priv->notify_port);
1658 if (kret != KERN_SUCCESS)
1659 error (_("Unable to create notification port, mach_port_allocate "
1660 "returned: %d"),
1661 kret);
1663 kret = mach_port_move_member (gdb_task,
1664 priv->notify_port, darwin_port_set);
1665 if (kret != KERN_SUCCESS)
1666 error (_("Unable to move notification port into new port set, "
1667 "mach_port_move_member\n"
1668 "returned: %d"),
1669 kret);
1671 darwin_setup_request_notification (inf);
1673 darwin_setup_exceptions (inf);
1675 catch (const gdb_exception &ex)
1677 exit_inferior (inf);
1678 switch_to_no_thread ();
1680 throw;
1683 target_ops *darwin_ops = get_native_target ();
1684 if (!inf->target_is_pushed (darwin_ops))
1685 inf->push_target (darwin_ops);
1688 /* Get the thread_info object corresponding to this darwin_thread_info. */
1690 static struct thread_info *
1691 thread_info_from_private_thread_info (darwin_thread_info *pti)
1693 for (struct thread_info *it : all_threads ())
1695 darwin_thread_info *iter_pti = get_darwin_thread_info (it);
1697 if (iter_pti->gdb_port == pti->gdb_port)
1698 return it;
1701 gdb_assert_not_reached ("did not find gdb thread for darwin thread");
1704 void
1705 darwin_nat_target::init_thread_list (inferior *inf)
1707 check_new_threads (inf);
1709 darwin_inferior *priv = get_darwin_inferior (inf);
1711 gdb_assert (!priv->threads.empty ());
1713 darwin_thread_info *first_pti = priv->threads.front ();
1714 struct thread_info *first_thread
1715 = thread_info_from_private_thread_info (first_pti);
1717 switch_to_thread (first_thread);
1720 /* The child must synchronize with gdb: gdb must set the exception port
1721 before the child call PTRACE_SIGEXC. We use a pipe to achieve this.
1722 FIXME: is there a lighter way ? */
1723 static int ptrace_fds[2];
1725 static void
1726 darwin_ptrace_me (void)
1728 int res;
1729 char c;
1731 /* Close write end point. */
1732 if (close (ptrace_fds[1]) < 0)
1733 trace_start_error_with_name ("close");
1735 /* Wait until gdb is ready. */
1736 res = read (ptrace_fds[0], &c, 1);
1737 if (res != 0)
1738 trace_start_error (_("unable to read from pipe, read returned: %d"), res);
1740 if (close (ptrace_fds[0]) < 0)
1741 trace_start_error_with_name ("close");
1743 /* Get rid of privileges. */
1744 if (setegid (getgid ()) < 0)
1745 trace_start_error_with_name ("setegid");
1747 /* Set TRACEME. */
1748 if (PTRACE (PT_TRACE_ME, 0, 0, 0) < 0)
1749 trace_start_error_with_name ("PTRACE");
1751 /* Redirect signals to exception port. */
1752 if (PTRACE (PT_SIGEXC, 0, 0, 0) < 0)
1753 trace_start_error_with_name ("PTRACE");
1756 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2). */
1757 static void
1758 darwin_pre_ptrace (void)
1760 if (pipe (ptrace_fds) != 0)
1762 ptrace_fds[0] = -1;
1763 ptrace_fds[1] = -1;
1764 error (_("unable to create a pipe: %s"), safe_strerror (errno));
1767 mark_fd_no_cloexec (ptrace_fds[0]);
1768 mark_fd_no_cloexec (ptrace_fds[1]);
1771 void
1772 darwin_nat_target::ptrace_him (int pid)
1774 struct inferior *inf = current_inferior ();
1776 darwin_attach_pid (inf);
1778 /* Let's the child run. */
1779 ::close (ptrace_fds[0]);
1780 ::close (ptrace_fds[1]);
1782 unmark_fd_no_cloexec (ptrace_fds[0]);
1783 unmark_fd_no_cloexec (ptrace_fds[1]);
1785 init_thread_list (inf);
1787 gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
1790 static void
1791 darwin_execvp (const char *file, char * const argv[], char * const env[])
1793 posix_spawnattr_t attr;
1794 short ps_flags = 0;
1795 int res;
1797 res = posix_spawnattr_init (&attr);
1798 if (res != 0)
1800 gdb_printf
1801 (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
1802 return;
1805 /* Do like execve: replace the image. */
1806 ps_flags = POSIX_SPAWN_SETEXEC;
1808 /* Disable ASLR. The constant doesn't look to be available outside the
1809 kernel include files. */
1810 #ifndef _POSIX_SPAWN_DISABLE_ASLR
1811 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
1812 #endif
1813 ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
1814 res = posix_spawnattr_setflags (&attr, ps_flags);
1815 if (res != 0)
1817 gdb_printf (gdb_stderr, "Cannot set posix_spawn flags\n");
1818 return;
1821 posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
1824 /* Read kernel version, and return TRUE if this host may have System
1825 Integrity Protection (Sierra or later). */
1827 static bool
1828 may_have_sip ()
1830 char str[16];
1831 size_t sz = sizeof (str);
1832 int ret;
1834 ret = sysctlbyname ("kern.osrelease", str, &sz, NULL, 0);
1835 if (ret == 0 && sz < sizeof (str))
1837 unsigned long ver = strtoul (str, NULL, 10);
1838 if (ver >= 16)
1839 return true;
1841 return false;
1844 /* A helper for maybe_cache_shell. This copies the shell to the
1845 cache. It will throw an exception on any failure. */
1847 static void
1848 copy_shell_to_cache (const char *shell, const std::string &new_name)
1850 scoped_fd from_fd = gdb_open_cloexec (shell, O_RDONLY, 0);
1851 if (from_fd.get () < 0)
1852 error (_("Could not open shell (%s) for reading: %s"),
1853 shell, safe_strerror (errno));
1855 std::string new_dir = ldirname (new_name.c_str ());
1856 if (!mkdir_recursive (new_dir.c_str ()))
1857 error (_("Could not make cache directory \"%s\": %s"),
1858 new_dir.c_str (), safe_strerror (errno));
1860 gdb::char_vector temp_name = make_temp_filename (new_name);
1861 scoped_fd to_fd = gdb_mkostemp_cloexec (&temp_name[0]);
1862 gdb::unlinker unlink_file_on_error (temp_name.data ());
1864 if (to_fd.get () < 0)
1865 error (_("Could not open temporary file \"%s\" for writing: %s"),
1866 temp_name.data (), safe_strerror (errno));
1868 if (fcopyfile (from_fd.get (), to_fd.get (), nullptr,
1869 COPYFILE_STAT | COPYFILE_DATA) != 0)
1870 error (_("Could not copy shell to cache as \"%s\": %s"),
1871 temp_name.data (), safe_strerror (errno));
1873 /* Be sure that the caching is atomic so that we don't get bad
1874 results from multiple copies of gdb running at the same time. */
1875 if (rename (temp_name.data (), new_name.c_str ()) != 0)
1876 error (_("Could not rename shell cache file to \"%s\": %s"),
1877 new_name.c_str (), safe_strerror (errno));
1879 unlink_file_on_error.keep ();
1882 /* If $SHELL is restricted, try to cache a copy. Starting with El
1883 Capitan, macOS introduced System Integrity Protection. Among other
1884 things, this prevents certain executables from being ptrace'd. In
1885 particular, executables in /bin, like most shells, are affected.
1886 To work around this, while preserving command-line glob expansion
1887 and redirections, gdb will cache a copy of the shell. Return true
1888 if all is well -- either the shell is not subject to SIP or it has
1889 been successfully cached. Returns false if something failed. */
1891 static bool
1892 maybe_cache_shell ()
1894 /* SF_RESTRICTED is defined in sys/stat.h and lets us determine if a
1895 given file is subject to SIP. */
1896 #ifdef SF_RESTRICTED
1898 /* If a check fails we want to revert -- maybe the user deleted the
1899 cache while gdb was running, or something like that. */
1900 copied_shell = nullptr;
1902 const char *shell = get_shell ();
1903 if (!IS_ABSOLUTE_PATH (shell))
1905 warning (_("This version of macOS has System Integrity Protection.\n\
1906 Normally gdb would try to work around this by caching a copy of your shell,\n\
1907 but because your shell (%s) is not an absolute path, this is being skipped."),
1908 shell);
1909 return false;
1912 struct stat sb;
1913 if (stat (shell, &sb) < 0)
1915 warning (_("This version of macOS has System Integrity Protection.\n\
1916 Normally gdb would try to work around this by caching a copy of your shell,\n\
1917 but because gdb could not stat your shell (%s), this is being skipped.\n\
1918 The error was: %s"),
1919 shell, safe_strerror (errno));
1920 return false;
1923 if ((sb.st_flags & SF_RESTRICTED) == 0)
1924 return true;
1926 /* Put the copy somewhere like ~/Library/Caches/gdb/bin/sh. */
1927 std::string new_name = get_standard_cache_dir ();
1928 /* There's no need to insert a directory separator here, because
1929 SHELL is known to be absolute. */
1930 new_name.append (shell);
1932 /* Maybe it was cached by some earlier gdb. */
1933 if (stat (new_name.c_str (), &sb) != 0 || !S_ISREG (sb.st_mode))
1937 copy_shell_to_cache (shell, new_name);
1939 catch (const gdb_exception_error &ex)
1941 warning (_("This version of macOS has System Integrity Protection.\n\
1942 Because `startup-with-shell' is enabled, gdb tried to work around SIP by\n\
1943 caching a copy of your shell. However, this failed:\n\
1944 %s\n\
1945 If you correct the problem, gdb will automatically try again the next time\n\
1946 you \"%ps\". To prevent these attempts, you can use:\n\
1947 %ps"),
1948 ex.what (),
1949 styled_string (command_style.style (), "run"),
1950 styled_string (command_style.style (),
1951 "set startup-with-shell off"));
1952 return false;
1955 gdb_printf (_("Note: this version of macOS has System Integrity Protection.\n\
1956 Because `startup-with-shell' is enabled, gdb has worked around this by\n\
1957 caching a copy of your shell. The shell used by \"%ps\" is now:\n\
1958 %s\n"),
1959 styled_string (command_style.style (), "run"),
1960 new_name.c_str ());
1963 /* We need to make sure that the new name has the correct lifetime. */
1964 static std::string saved_shell = std::move (new_name);
1965 copied_shell = saved_shell.c_str ();
1967 #endif /* SF_RESTRICTED */
1969 return true;
1972 void
1973 darwin_nat_target::create_inferior (const char *exec_file,
1974 const std::string &allargs,
1975 char **env, int from_tty)
1977 if (exec_file == nullptr)
1978 no_executable_specified_error ();
1980 std::optional<scoped_restore_tmpl<bool>> restore_startup_with_shell;
1981 darwin_nat_target *the_target = this;
1983 if (startup_with_shell && may_have_sip ())
1985 if (!maybe_cache_shell ())
1987 warning (_("startup-with-shell is now temporarily disabled"));
1988 restore_startup_with_shell.emplace (&startup_with_shell, 0);
1992 /* Do the hard work. */
1993 fork_inferior (exec_file, allargs, env, darwin_ptrace_me,
1994 [the_target] (int pid)
1996 the_target->ptrace_him (pid);
1998 darwin_pre_ptrace, copied_shell,
1999 darwin_execvp);
2003 /* Set things up such that the next call to darwin_wait will immediately
2004 return a fake stop event for inferior INF.
2006 This assumes that the inferior's thread list has been initialized,
2007 as it will suspend the inferior's first thread. */
2009 static void
2010 darwin_setup_fake_stop_event (struct inferior *inf)
2012 darwin_inferior *priv = get_darwin_inferior (inf);
2013 darwin_thread_t *thread;
2014 kern_return_t kret;
2016 gdb_assert (darwin_inf_fake_stop == NULL);
2017 darwin_inf_fake_stop = inf;
2019 /* When detecting a fake pending stop event, darwin_wait returns
2020 an event saying that the first thread is in a DARWIN_STOPPED
2021 state. To make that accurate, we need to suspend that thread
2022 as well. Otherwise, we'll try resuming it when resuming the
2023 inferior, and get a warning because the thread's suspend count
2024 is already zero, making the resume request useless. */
2025 thread = priv->threads[0];
2026 kret = thread_suspend (thread->gdb_port);
2027 MACH_CHECK_ERROR (kret);
2030 /* Attach to process PID, then initialize for debugging it
2031 and wait for the trace-trap that results from attaching. */
2032 void
2033 darwin_nat_target::attach (const char *args, int from_tty)
2035 pid_t pid;
2036 struct inferior *inf;
2038 pid = parse_pid_to_attach (args);
2040 if (pid == getpid ())
2041 error (_("I refuse to debug myself!"));
2043 target_announce_attach (from_tty, pid);
2045 if (pid == 0 || ::kill (pid, 0) < 0)
2046 error (_("Can't attach to process %d: %s (%d)"),
2047 pid, safe_strerror (errno), errno);
2049 inf = current_inferior ();
2050 inferior_appeared (inf, pid);
2051 inf->attach_flag = true;
2053 darwin_attach_pid (inf);
2055 darwin_suspend_inferior (inf);
2057 init_thread_list (inf);
2059 darwin_inferior *priv = get_darwin_inferior (inf);
2061 darwin_check_osabi (priv, inferior_ptid.tid ());
2063 darwin_setup_fake_stop_event (inf);
2065 priv->no_ptrace = 1;
2068 /* Take a program previously attached to and detaches it.
2069 The program resumes execution and will no longer stop
2070 on signals, etc. We'd better not have left any breakpoints
2071 in the program or it'll die when it hits one. For this
2072 to work, it may be necessary for the process to have been
2073 previously attached. It *might* work if the program was
2074 started via fork. */
2076 void
2077 darwin_nat_target::detach (inferior *inf, int from_tty)
2079 darwin_inferior *priv = get_darwin_inferior (inf);
2080 kern_return_t kret;
2081 int res;
2083 /* Display message. */
2084 target_announce_detach (from_tty);
2086 /* If ptrace() is in use, stop the process. */
2087 if (!priv->no_ptrace)
2088 stop_inferior (inf);
2090 kret = darwin_restore_exception_ports (priv);
2091 MACH_CHECK_ERROR (kret);
2093 if (!priv->no_ptrace)
2095 res = PTRACE (PT_DETACH, inf->pid, 0, 0);
2096 if (res != 0)
2097 warning (_("Unable to detach from process-id %d: %s (%d)"),
2098 inf->pid, safe_strerror (errno), errno);
2101 darwin_reply_to_all_pending_messages (inf);
2103 /* When using ptrace, we have just performed a PT_DETACH, which
2104 resumes the inferior. On the other hand, when we are not using
2105 ptrace, we need to resume its execution ourselves. */
2106 if (priv->no_ptrace)
2107 darwin_resume_inferior (inf);
2109 mourn_inferior ();
2112 std::string
2113 darwin_nat_target::pid_to_str (ptid_t ptid)
2115 long tid = ptid.tid ();
2117 if (tid != 0)
2118 return string_printf (_("Thread 0x%lx of process %u"),
2119 tid, ptid.pid ());
2121 return normal_pid_to_str (ptid);
2124 bool
2125 darwin_nat_target::thread_alive (ptid_t ptid)
2127 return true;
2130 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
2131 copy it to RDADDR in gdb's address space.
2132 If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
2133 to ADDR in inferior task's address space.
2134 Return 0 on failure; number of bytes read / written otherwise. */
2136 static int
2137 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
2138 gdb_byte *rdaddr, const gdb_byte *wraddr,
2139 ULONGEST length)
2141 kern_return_t kret;
2142 mach_vm_size_t res_length = 0;
2144 inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
2145 task, core_addr_to_string (addr), pulongest (length));
2147 /* First read. */
2148 if (rdaddr != NULL)
2150 mach_vm_size_t count;
2152 /* According to target.h(to_xfer_partial), one and only one may be
2153 non-null. */
2154 gdb_assert (wraddr == NULL);
2156 kret = mach_vm_read_overwrite (task, addr, length,
2157 (mach_vm_address_t) rdaddr, &count);
2158 if (kret != KERN_SUCCESS)
2160 inferior_debug
2161 (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
2162 core_addr_to_string (addr), mach_error_string (kret));
2163 return 0;
2165 return count;
2168 /* See above. */
2169 gdb_assert (wraddr != NULL);
2171 while (length != 0)
2173 mach_vm_address_t offset = addr & (mach_page_size - 1);
2174 mach_vm_address_t region_address = (mach_vm_address_t) (addr - offset);
2175 mach_vm_size_t aligned_length =
2176 (mach_vm_size_t) PAGE_ROUND (offset + length);
2177 vm_region_submap_short_info_data_64_t info;
2178 mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
2179 natural_t region_depth = 1000;
2180 mach_vm_address_t region_start = region_address;
2181 mach_vm_size_t region_length;
2182 mach_vm_size_t write_length;
2184 /* Read page protection. */
2185 kret = mach_vm_region_recurse
2186 (task, &region_start, &region_length, &region_depth,
2187 (vm_region_recurse_info_t) &info, &count);
2189 if (kret != KERN_SUCCESS)
2191 inferior_debug (1, _("darwin_read_write_inferior: "
2192 "mach_vm_region_recurse failed at %s: %s\n"),
2193 core_addr_to_string (region_address),
2194 mach_error_string (kret));
2195 return res_length;
2198 inferior_debug
2199 (9, _("darwin_read_write_inferior: "
2200 "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
2201 core_addr_to_string (region_address),
2202 core_addr_to_string (region_start),
2203 core_addr_to_string (region_length));
2205 /* Check for holes in memory. */
2206 if (region_start > region_address)
2208 warning (_("No memory at %s (vs %s+0x%x). Nothing written"),
2209 core_addr_to_string (region_address),
2210 core_addr_to_string (region_start),
2211 (unsigned)region_length);
2212 return res_length;
2215 /* Adjust the length. */
2216 region_length -= (region_address - region_start);
2217 if (region_length > aligned_length)
2218 region_length = aligned_length;
2220 /* Make the pages RW. */
2221 if (!(info.protection & VM_PROT_WRITE))
2223 vm_prot_t prot = VM_PROT_READ | VM_PROT_WRITE;
2225 kret = mach_vm_protect (task, region_address, region_length,
2226 FALSE, prot);
2227 if (kret != KERN_SUCCESS)
2229 prot |= VM_PROT_COPY;
2230 kret = mach_vm_protect (task, region_address, region_length,
2231 FALSE, prot);
2233 if (kret != KERN_SUCCESS)
2235 warning (_("darwin_read_write_inferior: "
2236 "mach_vm_protect failed at %s "
2237 "(len=0x%lx, prot=0x%x): %s"),
2238 core_addr_to_string (region_address),
2239 (unsigned long) region_length, (unsigned) prot,
2240 mach_error_string (kret));
2241 return res_length;
2245 if (offset + length > region_length)
2246 write_length = region_length - offset;
2247 else
2248 write_length = length;
2250 /* Write. */
2251 kret = mach_vm_write (task, addr, (vm_offset_t) wraddr, write_length);
2252 if (kret != KERN_SUCCESS)
2254 warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
2255 mach_error_string (kret));
2256 return res_length;
2259 /* Restore page rights. */
2260 if (!(info.protection & VM_PROT_WRITE))
2262 kret = mach_vm_protect (task, region_address, region_length,
2263 FALSE, info.protection);
2264 if (kret != KERN_SUCCESS)
2266 warning (_("darwin_read_write_inferior: "
2267 "mach_vm_protect restore failed at %s "
2268 "(len=0x%lx): %s"),
2269 core_addr_to_string (region_address),
2270 (unsigned long) region_length,
2271 mach_error_string (kret));
2275 addr += write_length;
2276 wraddr += write_length;
2277 res_length += write_length;
2278 length -= write_length;
2281 return res_length;
2284 /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
2285 to RDADDR (in big endian).
2286 Return 0 on failure; number of bytes read / written otherwise. */
2288 #ifdef TASK_DYLD_INFO_COUNT
2289 /* This is not available in Darwin 9. */
2290 static enum target_xfer_status
2291 darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
2292 ULONGEST length, ULONGEST *xfered_len)
2294 struct task_dyld_info task_dyld_info;
2295 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
2296 kern_return_t kret;
2298 if (addr != 0 || length > sizeof (mach_vm_address_t))
2299 return TARGET_XFER_EOF;
2301 kret = task_info (task, TASK_DYLD_INFO,
2302 (task_info_t) &task_dyld_info, &count);
2303 MACH_CHECK_ERROR (kret);
2304 if (kret != KERN_SUCCESS)
2305 return TARGET_XFER_E_IO;
2307 store_unsigned_integer (rdaddr, length, BFD_ENDIAN_BIG,
2308 task_dyld_info.all_image_info_addr);
2309 *xfered_len = (ULONGEST) length;
2310 return TARGET_XFER_OK;
2312 #endif
2316 enum target_xfer_status
2317 darwin_nat_target::xfer_partial (enum target_object object, const char *annex,
2318 gdb_byte *readbuf, const gdb_byte *writebuf,
2319 ULONGEST offset, ULONGEST len,
2320 ULONGEST *xfered_len)
2322 struct inferior *inf = current_inferior ();
2323 darwin_inferior *priv = get_darwin_inferior (inf);
2325 inferior_debug
2326 (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
2327 core_addr_to_string (offset), pulongest (len),
2328 host_address_to_string (readbuf), host_address_to_string (writebuf),
2329 inf->pid);
2331 switch (object)
2333 case TARGET_OBJECT_MEMORY:
2335 int l = darwin_read_write_inferior (priv->task, offset,
2336 readbuf, writebuf, len);
2338 if (l == 0)
2339 return TARGET_XFER_EOF;
2340 else
2342 gdb_assert (l > 0);
2343 *xfered_len = (ULONGEST) l;
2344 return TARGET_XFER_OK;
2347 #ifdef TASK_DYLD_INFO_COUNT
2348 case TARGET_OBJECT_DARWIN_DYLD_INFO:
2349 if (writebuf != NULL || readbuf == NULL)
2351 /* Support only read. */
2352 return TARGET_XFER_E_IO;
2354 return darwin_read_dyld_info (priv->task, offset, readbuf, len,
2355 xfered_len);
2356 #endif
2357 default:
2358 return TARGET_XFER_E_IO;
2363 static void
2364 set_enable_mach_exceptions (const char *args, int from_tty,
2365 struct cmd_list_element *c)
2367 if (inferior_ptid != null_ptid)
2369 struct inferior *inf = current_inferior ();
2370 darwin_inferior *priv = get_darwin_inferior (inf);
2371 exception_mask_t mask;
2372 kern_return_t kret;
2374 if (enable_mach_exceptions)
2375 mask = EXC_MASK_ALL;
2376 else
2378 darwin_restore_exception_ports (priv);
2379 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
2381 kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
2382 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
2383 MACH_CHECK_ERROR (kret);
2387 const char *
2388 darwin_nat_target::pid_to_exec_file (int pid)
2390 static char path[PATH_MAX];
2391 int res;
2393 res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
2394 if (res >= 0)
2395 return path;
2396 else
2397 return NULL;
2400 ptid_t
2401 darwin_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
2403 struct inferior *inf = current_inferior ();
2404 darwin_inferior *priv = get_darwin_inferior (inf);
2405 kern_return_t kret;
2406 mach_port_name_array_t names;
2407 mach_msg_type_number_t names_count;
2408 mach_port_type_array_t types;
2409 mach_msg_type_number_t types_count;
2410 long res = 0;
2412 /* First linear search. */
2413 for (darwin_thread_t *t : priv->threads)
2415 if (t->inf_port == lwp)
2416 return ptid_t (inferior_ptid.pid (), 0, t->gdb_port);
2419 /* Maybe the port was never extract. Do it now. */
2421 /* First get inferior port names. */
2422 kret = mach_port_names (priv->task, &names, &names_count, &types,
2423 &types_count);
2424 MACH_CHECK_ERROR (kret);
2425 if (kret != KERN_SUCCESS)
2426 return null_ptid;
2428 /* For each name, copy the right in the gdb space and then compare with
2429 our view of the inferior threads. We don't forget to deallocate the
2430 right. */
2431 for (int i = 0; i < names_count; i++)
2433 mach_port_t local_name;
2434 mach_msg_type_name_t local_type;
2436 /* We just need to know the corresponding name in gdb name space.
2437 So extract and deallocate the right. */
2438 kret = mach_port_extract_right (priv->task, names[i],
2439 MACH_MSG_TYPE_COPY_SEND,
2440 &local_name, &local_type);
2441 if (kret != KERN_SUCCESS)
2442 continue;
2443 mach_port_deallocate (gdb_task, local_name);
2445 for (darwin_thread_t *t : priv->threads)
2447 if (t->gdb_port == local_name)
2449 t->inf_port = names[i];
2450 if (names[i] == lwp)
2451 res = t->gdb_port;
2456 vm_deallocate (gdb_task, (vm_address_t) names,
2457 names_count * sizeof (mach_port_t));
2459 if (res)
2460 return ptid_t (current_inferior ()->pid, 0, res);
2461 else
2462 return null_ptid;
2465 bool
2466 darwin_nat_target::supports_multi_process ()
2468 return true;
2471 void _initialize_darwin_nat ();
2472 void
2473 _initialize_darwin_nat ()
2475 kern_return_t kret;
2477 gdb_task = mach_task_self ();
2478 darwin_host_self = mach_host_self ();
2480 /* Read page size. */
2481 kret = host_page_size (darwin_host_self, &mach_page_size);
2482 if (kret != KERN_SUCCESS)
2484 mach_page_size = 0x1000;
2485 MACH_CHECK_ERROR (kret);
2488 inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"),
2489 (unsigned long) mach_task_self (), getpid ());
2491 add_setshow_zuinteger_cmd ("darwin", class_obscure,
2492 &darwin_debug_flag, _("\
2493 Set if printing inferior communication debugging statements."), _("\
2494 Show if printing inferior communication debugging statements."), NULL,
2495 NULL, NULL,
2496 &setdebuglist, &showdebuglist);
2498 add_setshow_boolean_cmd ("mach-exceptions", class_support,
2499 &enable_mach_exceptions, _("\
2500 Set if mach exceptions are caught."), _("\
2501 Show if mach exceptions are caught."), _("\
2502 When this mode is on, all low level exceptions are reported before being\n\
2503 reported by the kernel."),
2504 &set_enable_mach_exceptions, NULL,
2505 &setlist, &showlist);