1 /* Darwin support for GDB, the GNU debugger.
2 Copyright (C) 2008-2017 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/>. */
31 #include "gdbthread.h"
33 #include "event-top.h"
36 #include "inf-child.h"
38 #include "arch-utils.h"
40 #include "bfd/mach-o.h"
42 #include <sys/ptrace.h>
43 #include <sys/signal.h>
45 #include <sys/types.h>
49 #include <sys/sysctl.h>
52 #include <sys/syscall.h>
55 #include <mach/mach_error.h>
56 #include <mach/mach_vm.h>
57 #include <mach/mach_init.h>
58 #include <mach/vm_map.h>
59 #include <mach/task.h>
60 #include <mach/mach_port.h>
61 #include <mach/thread_act.h>
62 #include <mach/port.h>
64 #include "darwin-nat.h"
65 #include "common/filestuff.h"
66 #include "nat/fork-inferior.h"
69 Darwin kernel is Mach + BSD derived kernel. Note that they share the
70 same memory space and are linked together (ie there is no micro-kernel).
72 Although ptrace(2) is available on Darwin, it is not complete. We have
73 to use Mach calls to read and write memory and to modify registers. We
74 also use Mach to get inferior faults. As we cannot use select(2) or
75 signals with Mach port (the Mach communication channel), signals are
76 reported to gdb as an exception. Furthermore we detect death of the
77 inferior through a Mach notification message. This way we only wait
80 Some Mach documentation is available for Apple xnu source package or
84 #define PTRACE(CMD, PID, ADDR, SIG) \
85 darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
87 static void darwin_interrupt (struct target_ops *self, ptid_t);
89 static void darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
90 enum gdb_signal signal);
91 static void darwin_resume (ptid_t ptid, int step,
92 enum gdb_signal signal);
94 static ptid_t darwin_wait_to (struct target_ops *ops, ptid_t ptid,
95 struct target_waitstatus *status, int options);
96 static ptid_t darwin_wait (ptid_t ptid, struct target_waitstatus *status);
98 static void darwin_mourn_inferior (struct target_ops *ops);
100 static void darwin_kill_inferior (struct target_ops *ops);
102 static void darwin_ptrace_me (void);
104 static void darwin_ptrace_him (int pid);
106 static void darwin_create_inferior (struct target_ops *ops,
107 const char *exec_file,
108 const std::string &allargs,
109 char **env, int from_tty);
111 static void darwin_files_info (struct target_ops *ops);
113 static const char *darwin_pid_to_str (struct target_ops *ops, ptid_t tpid);
115 static int darwin_thread_alive (struct target_ops *ops, ptid_t tpid);
117 static void darwin_encode_reply (mig_reply_error_t *reply,
118 mach_msg_header_t *hdr, integer_t code);
120 static void darwin_setup_request_notification (struct inferior *inf);
121 static void darwin_deallocate_exception_ports (darwin_inferior *inf);
122 static void darwin_setup_exceptions (struct inferior *inf);
123 static void darwin_deallocate_threads (struct inferior *inf);
125 /* Target operations for Darwin. */
126 static struct target_ops *darwin_ops;
128 /* Task identifier of gdb. */
129 static task_t gdb_task;
131 /* A copy of mach_host_self (). */
132 mach_port_t darwin_host_self;
134 /* Exception port. */
135 mach_port_t darwin_ex_port;
137 /* Port set, to wait for answer on all ports. */
138 mach_port_t darwin_port_set;
141 static vm_size_t mach_page_size;
143 /* If Set, catch all mach exceptions (before they are converted to signals
145 static int enable_mach_exceptions;
147 /* Inferior that should report a fake stop event. */
148 static struct inferior *darwin_inf_fake_stop;
150 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
151 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
153 /* This controls output of inferior debugging. */
154 static unsigned int darwin_debug_flag = 0;
156 /* Create a __TEXT __info_plist section in the executable so that gdb could
157 be signed. This is required to get an authorization for task_for_pid.
159 Once gdb is built, you must codesign it with any system-trusted signing
160 authority. See taskgated(8) for details. */
161 static const unsigned char info_plist[]
162 __attribute__ ((section ("__TEXT,__info_plist"),used)) =
163 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
164 "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
165 " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
166 "<plist version=\"1.0\">\n"
168 " <key>CFBundleIdentifier</key>\n"
169 " <string>org.gnu.gdb</string>\n"
170 " <key>CFBundleName</key>\n"
171 " <string>gdb</string>\n"
172 " <key>CFBundleVersion</key>\n"
173 " <string>1.0</string>\n"
174 " <key>SecTaskAccess</key>\n"
176 " <string>allowed</string>\n"
177 " <string>debug</string>\n"
182 static void inferior_debug (int level, const char *fmt, ...)
183 ATTRIBUTE_PRINTF (2, 3);
186 inferior_debug (int level, const char *fmt, ...)
190 if (darwin_debug_flag < level)
194 printf_unfiltered (_("[%d inferior]: "), getpid ());
195 vprintf_unfiltered (fmt, ap);
200 mach_check_error (kern_return_t ret, const char *file,
201 unsigned int line, const char *func)
203 if (ret == KERN_SUCCESS)
206 func = _("[UNKNOWN]");
208 warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
209 file, line, func, mach_error_string (ret), (unsigned long) ret);
213 unparse_exception_type (unsigned int i)
215 static char unknown_exception_buf[32];
220 return "EXC_BAD_ACCESS";
221 case EXC_BAD_INSTRUCTION:
222 return "EXC_BAD_INSTRUCTION";
224 return "EXC_ARITHMETIC";
226 return "EXC_EMULATION";
228 return "EXC_SOFTWARE";
230 return "EXC_BREAKPOINT";
232 return "EXC_SYSCALL";
233 case EXC_MACH_SYSCALL:
234 return "EXC_MACH_SYSCALL";
236 return "EXC_RPC_ALERT";
240 snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
241 return unknown_exception_buf;
245 /* Set errno to zero, and then call ptrace with the given arguments.
246 If inferior debugging traces are on, then also print a debug
249 The returned value is the same as the value returned by ptrace,
250 except in the case where that value is -1 but errno is zero.
251 This case is documented to be a non-error situation, so we
252 return zero in that case. */
255 darwin_ptrace (const char *name,
256 int request, int pid, caddr_t arg3, int arg4)
261 ret = ptrace (request, pid, arg3, arg4);
262 if (ret == -1 && errno == 0)
265 inferior_debug (4, _("ptrace (%s, %d, 0x%lx, %d): %d (%s)\n"),
266 name, pid, (unsigned long) arg3, arg4, ret,
267 (ret != 0) ? safe_strerror (errno) : _("no error"));
272 cmp_thread_t (const void *l, const void *r)
274 thread_t tl = *(const thread_t *)l;
275 thread_t tr = *(const thread_t *)r;
276 return (int)(tl - tr);
280 darwin_check_new_threads (struct inferior *inf)
284 thread_array_t thread_list;
285 unsigned int new_nbr;
286 unsigned int old_nbr;
287 unsigned int new_ix, old_ix;
288 darwin_inferior *darwin_inf = inf->priv;
289 VEC (darwin_thread_t) *thread_vec;
291 /* Get list of threads. */
292 kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
293 MACH_CHECK_ERROR (kret);
294 if (kret != KERN_SUCCESS)
299 qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
301 if (darwin_inf->threads)
302 old_nbr = VEC_length (darwin_thread_t, darwin_inf->threads);
306 /* Quick check for no changes. */
307 if (old_nbr == new_nbr)
309 for (i = 0; i < new_nbr; i++)
311 != VEC_index (darwin_thread_t, darwin_inf->threads, i)->gdb_port)
315 /* Deallocate ports. */
316 for (i = 0; i < new_nbr; i++)
318 kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
319 MACH_CHECK_ERROR (kret);
322 /* Deallocate the buffer. */
323 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
324 new_nbr * sizeof (int));
325 MACH_CHECK_ERROR (kret);
331 /* Full handling: detect new threads, remove dead threads. */
332 thread_vec = VEC_alloc (darwin_thread_t, new_nbr);
334 for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
336 thread_t new_id = (new_ix < new_nbr) ?
337 thread_list[new_ix] : THREAD_NULL;
338 darwin_thread_t *old = (old_ix < old_nbr) ?
339 VEC_index (darwin_thread_t, darwin_inf->threads, old_ix) : NULL;
340 thread_t old_id = old ? old->gdb_port : THREAD_NULL;
343 (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
344 new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
346 if (old_id == new_id)
348 /* Thread still exist. */
349 VEC_safe_push (darwin_thread_t, thread_vec, old);
353 /* Deallocate the port. */
354 kret = mach_port_deallocate (gdb_task, new_id);
355 MACH_CHECK_ERROR (kret);
359 if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
361 /* Ignore dead ports.
362 In some weird cases, we might get dead ports. They should
363 correspond to dead thread so they could safely be ignored. */
367 if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
369 /* A thread was created. */
370 struct private_thread_info *pti;
372 pti = XCNEW (struct private_thread_info);
373 pti->gdb_port = new_id;
374 pti->msg_state = DARWIN_RUNNING;
376 /* Add the new thread. */
377 add_thread_with_info (ptid_build (inf->pid, 0, new_id), pti);
378 VEC_safe_push (darwin_thread_t, thread_vec, pti);
382 if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
384 /* A thread was removed. */
385 delete_thread (ptid_build (inf->pid, 0, old_id));
386 kret = mach_port_deallocate (gdb_task, old_id);
387 MACH_CHECK_ERROR (kret);
391 gdb_assert_not_reached ("unexpected thread case");
394 if (darwin_inf->threads)
395 VEC_free (darwin_thread_t, darwin_inf->threads);
396 darwin_inf->threads = thread_vec;
398 /* Deallocate the buffer. */
399 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
400 new_nbr * sizeof (int));
401 MACH_CHECK_ERROR (kret);
405 find_inferior_task_it (struct inferior *inf, void *port_ptr)
407 return inf->priv->task == *(task_t *)port_ptr;
411 find_inferior_pid_it (struct inferior *inf, void *pid_ptr)
413 return inf->pid == *(int *)pid_ptr;
416 /* Return an inferior by task port. */
417 static struct inferior *
418 darwin_find_inferior_by_task (task_t port)
420 return iterate_over_inferiors (&find_inferior_task_it, &port);
423 /* Return an inferior by pid port. */
424 static struct inferior *
425 darwin_find_inferior_by_pid (int pid)
427 return iterate_over_inferiors (&find_inferior_pid_it, &pid);
430 /* Return a thread by port. */
431 static darwin_thread_t *
432 darwin_find_thread (struct inferior *inf, thread_t thread)
438 VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
440 if (t->gdb_port == thread)
445 /* Suspend (ie stop) an inferior at Mach level. */
448 darwin_suspend_inferior (struct inferior *inf)
450 if (!inf->priv->suspended)
454 kret = task_suspend (inf->priv->task);
455 MACH_CHECK_ERROR (kret);
457 inf->priv->suspended = 1;
461 /* Resume an inferior at Mach level. */
464 darwin_resume_inferior (struct inferior *inf)
466 if (inf->priv->suspended)
470 kret = task_resume (inf->priv->task);
471 MACH_CHECK_ERROR (kret);
473 inf->priv->suspended = 0;
477 /* Iterator functions. */
480 darwin_suspend_inferior_it (struct inferior *inf, void *arg)
482 darwin_suspend_inferior (inf);
483 darwin_check_new_threads (inf);
488 darwin_resume_inferior_it (struct inferior *inf, void *arg)
490 darwin_resume_inferior (inf);
495 darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
497 printf_unfiltered (_("message header:\n"));
498 printf_unfiltered (_(" bits: 0x%x\n"), hdr->msgh_bits);
499 printf_unfiltered (_(" size: 0x%x\n"), hdr->msgh_size);
500 printf_unfiltered (_(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
501 printf_unfiltered (_(" local-port: 0x%x\n"), hdr->msgh_local_port);
502 printf_unfiltered (_(" reserved: 0x%x\n"), hdr->msgh_reserved);
503 printf_unfiltered (_(" id: 0x%x\n"), hdr->msgh_id);
507 const unsigned char *data;
508 const unsigned int *ldata;
512 data = (unsigned char *)(hdr + 1);
513 size = hdr->msgh_size - sizeof (mach_msg_header_t);
515 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
517 mach_msg_body_t *bod = (mach_msg_body_t*)data;
518 mach_msg_port_descriptor_t *desc =
519 (mach_msg_port_descriptor_t *)(bod + 1);
522 printf_unfiltered (_("body: descriptor_count=%u\n"),
523 bod->msgh_descriptor_count);
524 data += sizeof (mach_msg_body_t);
525 size -= sizeof (mach_msg_body_t);
526 for (k = 0; k < bod->msgh_descriptor_count; k++)
527 switch (desc[k].type)
529 case MACH_MSG_PORT_DESCRIPTOR:
531 (_(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
532 k, desc[k].type, desc[k].name, desc[k].disposition);
535 printf_unfiltered (_(" descr %d: type=%u\n"),
539 data += bod->msgh_descriptor_count
540 * sizeof (mach_msg_port_descriptor_t);
541 size -= bod->msgh_descriptor_count
542 * sizeof (mach_msg_port_descriptor_t);
543 ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
545 (_("NDR: mig=%02x if=%02x encod=%02x "
546 "int=%02x char=%02x float=%02x\n"),
547 ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
548 ndr->int_rep, ndr->char_rep, ndr->float_rep);
549 data += sizeof (NDR_record_t);
550 size -= sizeof (NDR_record_t);
553 printf_unfiltered (_(" data:"));
554 ldata = (const unsigned int *)data;
555 for (i = 0; i < size / sizeof (unsigned int); i++)
556 printf_unfiltered (" %08x", ldata[i]);
557 printf_unfiltered (_("\n"));
561 /* Adjust inferior data when a new task was created. */
563 static struct inferior *
564 darwin_find_new_inferior (task_t task_port, thread_t thread_port)
567 struct inferior *inf;
571 /* Find the corresponding pid. */
572 kret = pid_for_task (task_port, &task_pid);
573 if (kret != KERN_SUCCESS)
575 MACH_CHECK_ERROR (kret);
579 /* Find the inferior for this pid. */
580 inf = darwin_find_inferior_by_pid (task_pid);
584 /* Deallocate saved exception ports. */
585 darwin_deallocate_exception_ports (inf->priv);
587 /* No need to remove dead_name notification, but still... */
588 kret = mach_port_request_notification (gdb_task, inf->priv->task,
589 MACH_NOTIFY_DEAD_NAME, 0,
591 MACH_MSG_TYPE_MAKE_SEND_ONCE,
593 if (kret != KERN_INVALID_ARGUMENT)
594 MACH_CHECK_ERROR (kret);
596 /* Replace old task port. */
597 kret = mach_port_deallocate (gdb_task, inf->priv->task);
598 MACH_CHECK_ERROR (kret);
599 inf->priv->task = task_port;
601 darwin_setup_request_notification (inf);
602 darwin_setup_exceptions (inf);
607 /* Check data representation. */
610 darwin_check_message_ndr (NDR_record_t *ndr)
612 if (ndr->mig_vers != NDR_PROTOCOL_2_0
613 || ndr->if_vers != NDR_PROTOCOL_2_0
614 || ndr->mig_encoding != NDR_record.mig_encoding
615 || ndr->int_rep != NDR_record.int_rep
616 || ndr->char_rep != NDR_record.char_rep
617 || ndr->float_rep != NDR_record.float_rep)
622 /* Decode an exception message. */
625 darwin_decode_exception_message (mach_msg_header_t *hdr,
626 struct inferior **pinf,
627 darwin_thread_t **pthread)
629 mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
630 mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
633 struct inferior *inf;
634 darwin_thread_t *thread;
636 thread_t thread_port;
640 /* Check message destination. */
641 if (hdr->msgh_local_port != darwin_ex_port)
644 /* Check message header. */
645 if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
648 /* Check descriptors. */
649 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
650 + sizeof (*ndr) + 2 * sizeof (integer_t))
651 || bod->msgh_descriptor_count != 2
652 || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
653 || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
654 || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
655 || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
658 /* Check data representation. */
659 ndr = (NDR_record_t *)(desc + 2);
660 if (darwin_check_message_ndr (ndr) != 0)
663 /* Ok, the hard work. */
664 data = (integer_t *)(ndr + 1);
666 task_port = desc[1].name;
667 thread_port = desc[0].name;
669 /* Find process by port. */
670 inf = darwin_find_inferior_by_task (task_port);
673 if (inf == NULL && data[0] == EXC_SOFTWARE && data[1] == 2
674 && data[2] == EXC_SOFT_SIGNAL && data[3] == SIGTRAP)
676 /* Not a known inferior, but a sigtrap. This happens on darwin 16.1.0,
677 as a new Mach task is created when a process exec. */
678 inf = darwin_find_new_inferior (task_port, thread_port);
683 /* Deallocate task_port, unless it was saved. */
684 kret = mach_port_deallocate (mach_task_self (), task_port);
685 MACH_CHECK_ERROR (kret);
690 /* We got new rights to the task, get rid of it. Do not get rid of
691 thread right, as we will need it to find the thread. */
692 kret = mach_port_deallocate (mach_task_self (), task_port);
693 MACH_CHECK_ERROR (kret);
698 /* Not a known inferior. This could happen if the child fork, as
699 the created process will inherit its exception port.
700 FIXME: should the exception port be restored ? */
702 mig_reply_error_t reply;
705 (4, _("darwin_decode_exception_message: unknown task 0x%x\n"),
708 /* Free thread port (we don't know it). */
709 kret = mach_port_deallocate (mach_task_self (), thread_port);
710 MACH_CHECK_ERROR (kret);
712 darwin_encode_reply (&reply, hdr, KERN_SUCCESS);
714 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
715 reply.Head.msgh_size, 0,
716 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
718 MACH_CHECK_ERROR (kret);
723 /* Find thread by port. */
724 /* Check for new threads. Do it early so that the port in the exception
725 message can be deallocated. */
726 darwin_check_new_threads (inf);
728 /* Free the thread port (as gdb knows the thread, it has already has a right
729 for it, so this just decrement a reference counter). */
730 kret = mach_port_deallocate (mach_task_self (), thread_port);
731 MACH_CHECK_ERROR (kret);
733 thread = darwin_find_thread (inf, thread_port);
738 /* The thread should be running. However we have observed cases where a
739 thread got a SIGTTIN message after being stopped. */
740 gdb_assert (thread->msg_state != DARWIN_MESSAGE);
742 /* Finish decoding. */
743 thread->event.header = *hdr;
744 thread->event.thread_port = thread_port;
745 thread->event.task_port = task_port;
746 thread->event.ex_type = data[0];
747 thread->event.data_count = data[1];
749 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
750 + sizeof (*ndr) + 2 * sizeof (integer_t)
751 + data[1] * sizeof (integer_t)))
753 for (i = 0; i < data[1]; i++)
754 thread->event.ex_data[i] = data[2 + i];
756 thread->msg_state = DARWIN_MESSAGE;
761 /* Decode dead_name notify message. */
764 darwin_decode_notify_message (mach_msg_header_t *hdr, struct inferior **pinf)
766 NDR_record_t *ndr = (NDR_record_t *)(hdr + 1);
767 integer_t *data = (integer_t *)(ndr + 1);
768 struct inferior *inf;
769 darwin_thread_t *thread;
771 thread_t thread_port;
775 /* Check message header. */
776 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
779 /* Check descriptors. */
780 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*ndr) + sizeof (integer_t)))
783 /* Check data representation. */
784 if (darwin_check_message_ndr (ndr) != 0)
789 /* Find process by port. */
790 inf = darwin_find_inferior_by_task (task_port);
793 /* Check message destination. */
794 if (inf != NULL && hdr->msgh_local_port != inf->priv->notify_port)
801 darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
804 mach_msg_header_t *rh = &reply->Head;
806 rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
807 rh->msgh_remote_port = hdr->msgh_remote_port;
808 rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
809 rh->msgh_local_port = MACH_PORT_NULL;
810 rh->msgh_id = hdr->msgh_id + 100;
812 reply->NDR = NDR_record;
813 reply->RetCode = code;
817 darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
820 mig_reply_error_t reply;
822 darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
824 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
825 reply.Head.msgh_size, 0,
826 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
828 MACH_CHECK_ERROR (kret);
830 inf->priv->pending_messages--;
834 darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
835 int step, int nsignal)
841 (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
842 thread->msg_state, thread->gdb_port, step, nsignal);
844 switch (thread->msg_state)
847 if (thread->event.ex_type == EXC_SOFTWARE
848 && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
850 /* Either deliver a new signal or cancel the signal received. */
851 res = PTRACE (PT_THUPDATE, inf->pid,
852 (caddr_t) (uintptr_t) thread->gdb_port, nsignal);
854 inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
858 /* Note: ptrace is allowed only if the process is stopped.
859 Directly send the signal to the thread. */
860 res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
861 inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
862 thread->gdb_port, nsignal, res);
863 thread->signaled = 1;
866 /* Set or reset single step. */
867 inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
868 thread->gdb_port, step);
869 darwin_set_sstep (thread->gdb_port, step);
870 thread->single_step = step;
872 darwin_send_reply (inf, thread);
873 thread->msg_state = DARWIN_RUNNING;
880 kret = thread_resume (thread->gdb_port);
881 MACH_CHECK_ERROR (kret);
883 thread->msg_state = DARWIN_RUNNING;
888 /* Resume all threads of the inferior. */
891 darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
893 darwin_thread_t *thread;
897 VEC_iterate (darwin_thread_t, inf->priv->threads, k, thread);
899 darwin_resume_thread (inf, thread, step, nsignal);
902 struct resume_inferior_threads_param
909 darwin_resume_inferior_threads_it (struct inferior *inf, void *param)
911 int step = ((struct resume_inferior_threads_param *)param)->step;
912 int nsignal = ((struct resume_inferior_threads_param *)param)->nsignal;
914 darwin_resume_inferior_threads (inf, step, nsignal);
919 /* Suspend all threads of INF. */
922 darwin_suspend_inferior_threads (struct inferior *inf)
924 darwin_thread_t *thread;
929 VEC_iterate (darwin_thread_t, inf->priv->threads, k, thread);
931 switch (thread->msg_state)
937 kret = thread_suspend (thread->gdb_port);
938 MACH_CHECK_ERROR (kret);
939 thread->msg_state = DARWIN_STOPPED;
945 darwin_resume (ptid_t ptid, int step, enum gdb_signal signal)
947 struct target_waitstatus status;
953 struct inferior *inf;
956 (2, _("darwin_resume: pid=%d, tid=0x%lx, step=%d, signal=%d\n"),
957 ptid_get_pid (ptid), ptid_get_tid (ptid), step, signal);
959 if (signal == GDB_SIGNAL_0)
962 nsignal = gdb_signal_to_host (signal);
964 /* Don't try to single step all threads. */
966 ptid = inferior_ptid;
968 /* minus_one_ptid is RESUME_ALL. */
969 if (ptid_equal (ptid, minus_one_ptid))
971 struct resume_inferior_threads_param param;
973 param.nsignal = nsignal;
976 /* Resume threads. */
977 iterate_over_inferiors (darwin_resume_inferior_threads_it, ¶m);
979 iterate_over_inferiors (darwin_resume_inferior_it, NULL);
983 struct inferior *inf = find_inferior_ptid (ptid);
984 long tid = ptid_get_tid (ptid);
986 /* Stop the inferior (should be useless). */
987 darwin_suspend_inferior (inf);
990 darwin_resume_inferior_threads (inf, step, nsignal);
993 darwin_thread_t *thread;
995 /* Suspend threads of the task. */
996 darwin_suspend_inferior_threads (inf);
998 /* Resume the selected thread. */
999 thread = darwin_find_thread (inf, tid);
1000 gdb_assert (thread);
1001 darwin_resume_thread (inf, thread, step, nsignal);
1004 /* Resume the task. */
1005 darwin_resume_inferior (inf);
1010 darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
1011 enum gdb_signal signal)
1013 return darwin_resume (ptid, step, signal);
1017 darwin_decode_message (mach_msg_header_t *hdr,
1018 darwin_thread_t **pthread,
1019 struct inferior **pinf,
1020 struct target_waitstatus *status)
1022 darwin_thread_t *thread;
1023 struct inferior *inf;
1025 /* Exception message. 2401 == 0x961 is exc. */
1026 if (hdr->msgh_id == 2401)
1030 /* Decode message. */
1031 res = darwin_decode_exception_message (hdr, &inf, &thread);
1035 /* Should not happen... */
1037 (_("darwin_wait: ill-formatted message (id=0x%x)\n"), hdr->msgh_id);
1038 /* FIXME: send a failure reply? */
1039 status->kind = TARGET_WAITKIND_IGNORE;
1040 return minus_one_ptid;
1044 status->kind = TARGET_WAITKIND_IGNORE;
1045 return minus_one_ptid;
1049 inf->priv->pending_messages++;
1051 status->kind = TARGET_WAITKIND_STOPPED;
1052 thread->msg_state = DARWIN_MESSAGE;
1054 inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
1056 unparse_exception_type (thread->event.ex_type));
1058 switch (thread->event.ex_type)
1060 case EXC_BAD_ACCESS:
1061 status->value.sig = GDB_EXC_BAD_ACCESS;
1063 case EXC_BAD_INSTRUCTION:
1064 status->value.sig = GDB_EXC_BAD_INSTRUCTION;
1066 case EXC_ARITHMETIC:
1067 status->value.sig = GDB_EXC_ARITHMETIC;
1070 status->value.sig = GDB_EXC_EMULATION;
1073 if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
1076 gdb_signal_from_host (thread->event.ex_data[1]);
1077 inferior_debug (5, _(" (signal %d: %s)\n"),
1078 thread->event.ex_data[1],
1079 gdb_signal_to_name (status->value.sig));
1081 /* If the thread is stopped because it has received a signal
1082 that gdb has just sent, continue. */
1083 if (thread->signaled)
1085 thread->signaled = 0;
1086 darwin_send_reply (inf, thread);
1087 thread->msg_state = DARWIN_RUNNING;
1088 status->kind = TARGET_WAITKIND_IGNORE;
1092 status->value.sig = GDB_EXC_SOFTWARE;
1094 case EXC_BREAKPOINT:
1095 /* Many internal GDB routines expect breakpoints to be reported
1096 as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
1097 as a spurious signal. */
1098 status->value.sig = GDB_SIGNAL_TRAP;
1101 status->value.sig = GDB_SIGNAL_UNKNOWN;
1105 return ptid_build (inf->pid, 0, thread->gdb_port);
1107 else if (hdr->msgh_id == 0x48)
1109 /* MACH_NOTIFY_DEAD_NAME: notification for exit. */
1112 res = darwin_decode_notify_message (hdr, &inf);
1116 /* Should not happen... */
1118 (_("darwin_wait: ill-formatted message (id=0x%x, res=%d)\n"),
1125 if (res < 0 || inf == NULL)
1127 status->kind = TARGET_WAITKIND_IGNORE;
1128 return minus_one_ptid;
1133 if (!inf->priv->no_ptrace)
1138 res = wait4 (inf->pid, &wstatus, 0, NULL);
1139 if (res < 0 || res != inf->pid)
1141 printf_unfiltered (_("wait4: res=%d: %s\n"),
1142 res, safe_strerror (errno));
1143 status->kind = TARGET_WAITKIND_IGNORE;
1144 return minus_one_ptid;
1146 if (WIFEXITED (wstatus))
1148 status->kind = TARGET_WAITKIND_EXITED;
1149 status->value.integer = WEXITSTATUS (wstatus);
1153 status->kind = TARGET_WAITKIND_SIGNALLED;
1154 status->value.sig = gdb_signal_from_host (WTERMSIG (wstatus));
1157 inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
1160 /* Looks necessary on Leopard and harmless... */
1161 wait4 (inf->pid, &wstatus, 0, NULL);
1163 inferior_ptid = ptid_build (inf->pid, 0, 0);
1164 return inferior_ptid;
1168 inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
1169 status->kind = TARGET_WAITKIND_EXITED;
1170 status->value.integer = 0; /* Don't know. */
1171 return ptid_build (inf->pid, 0, 0);
1176 /* Unknown message. */
1177 warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
1178 status->kind = TARGET_WAITKIND_IGNORE;
1179 return minus_one_ptid;
1183 cancel_breakpoint (ptid_t ptid)
1185 /* Arrange for a breakpoint to be hit again later. We will handle
1186 the current event, eventually we will resume this thread, and this
1187 breakpoint will trap again.
1189 If we do not do this, then we run the risk that the user will
1190 delete or disable the breakpoint, but the thread will have already
1193 struct regcache *regcache = get_thread_regcache (ptid);
1194 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1197 pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
1198 if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
1200 inferior_debug (4, "cancel_breakpoint for thread 0x%lx\n",
1201 (unsigned long) ptid_get_tid (ptid));
1203 /* Back up the PC if necessary. */
1204 if (gdbarch_decr_pc_after_break (gdbarch))
1205 regcache_write_pc (regcache, pc);
1213 darwin_wait (ptid_t ptid, struct target_waitstatus *status)
1218 mach_msg_header_t hdr;
1221 mach_msg_header_t *hdr = &msgin.hdr;
1223 darwin_thread_t *thread;
1224 struct inferior *inf;
1227 (2, _("darwin_wait: waiting for a message pid=%d thread=%lx\n"),
1228 ptid_get_pid (ptid), ptid_get_tid (ptid));
1230 /* Handle fake stop events at first. */
1231 if (darwin_inf_fake_stop != NULL)
1233 inf = darwin_inf_fake_stop;
1234 darwin_inf_fake_stop = NULL;
1236 status->kind = TARGET_WAITKIND_STOPPED;
1237 status->value.sig = GDB_SIGNAL_TRAP;
1238 thread = VEC_index (darwin_thread_t, inf->priv->threads, 0);
1239 thread->msg_state = DARWIN_STOPPED;
1240 return ptid_build (inf->pid, 0, thread->gdb_port);
1245 /* set_sigint_trap (); */
1247 /* Wait for a message. */
1248 kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1249 sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1251 /* clear_sigint_trap (); */
1253 if (kret == MACH_RCV_INTERRUPTED)
1255 status->kind = TARGET_WAITKIND_IGNORE;
1256 return minus_one_ptid;
1259 if (kret != MACH_MSG_SUCCESS)
1261 inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
1262 status->kind = TARGET_WAITKIND_SPURIOUS;
1263 return minus_one_ptid;
1266 /* Debug: display message. */
1267 if (darwin_debug_flag > 10)
1268 darwin_dump_message (hdr, darwin_debug_flag > 11);
1270 res = darwin_decode_message (hdr, &thread, &inf, status);
1271 if (ptid_equal (res, minus_one_ptid))
1274 /* Early return in case an inferior has exited. */
1278 while (status->kind == TARGET_WAITKIND_IGNORE);
1280 /* Stop all tasks. */
1281 iterate_over_inferiors (darwin_suspend_inferior_it, NULL);
1283 /* Read pending messages. */
1286 struct target_waitstatus status2;
1289 kret = mach_msg (&msgin.hdr,
1290 MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1291 sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1293 if (kret == MACH_RCV_TIMED_OUT)
1295 if (kret != MACH_MSG_SUCCESS)
1298 (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
1302 /* Debug: display message. */
1303 if (darwin_debug_flag > 10)
1304 darwin_dump_message (hdr, darwin_debug_flag > 11);
1306 ptid2 = darwin_decode_message (hdr, &thread, &inf, &status2);
1308 if (inf != NULL && thread != NULL
1309 && thread->event.ex_type == EXC_BREAKPOINT)
1311 if (thread->single_step
1312 || cancel_breakpoint (ptid_build (inf->pid, 0, thread->gdb_port)))
1314 gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1315 darwin_send_reply (inf, thread);
1316 thread->msg_state = DARWIN_RUNNING;
1320 (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
1324 inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1330 darwin_wait_to (struct target_ops *ops,
1331 ptid_t ptid, struct target_waitstatus *status, int options)
1333 return darwin_wait (ptid, status);
1337 darwin_interrupt (struct target_ops *self, ptid_t t)
1339 struct inferior *inf = current_inferior ();
1341 /* FIXME: handle in no_ptrace mode. */
1342 gdb_assert (!inf->priv->no_ptrace);
1343 kill (inf->pid, SIGINT);
1346 /* Deallocate threads port and vector. */
1349 darwin_deallocate_threads (struct inferior *inf)
1351 if (inf->priv->threads)
1357 VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
1360 kret = mach_port_deallocate (gdb_task, t->gdb_port);
1361 MACH_CHECK_ERROR (kret);
1363 VEC_free (darwin_thread_t, inf->priv->threads);
1364 inf->priv->threads = NULL;
1369 darwin_mourn_inferior (struct target_ops *ops)
1371 struct inferior *inf = current_inferior ();
1376 /* Deallocate threads. */
1377 darwin_deallocate_threads (inf);
1379 /* Remove notify_port from darwin_port_set. */
1380 kret = mach_port_move_member (gdb_task,
1381 inf->priv->notify_port, MACH_PORT_NULL);
1382 MACH_CHECK_ERROR (kret);
1384 /* Remove task port dead_name notification. */
1385 kret = mach_port_request_notification (gdb_task, inf->priv->task,
1386 MACH_NOTIFY_DEAD_NAME, 0,
1388 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1390 /* This can fail if the task is dead. */
1391 inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
1392 inf->priv->task, prev, inf->priv->notify_port);
1394 if (kret == KERN_SUCCESS)
1396 kret = mach_port_deallocate (gdb_task, prev);
1397 MACH_CHECK_ERROR (kret);
1400 /* Destroy notify_port. */
1401 kret = mach_port_destroy (gdb_task, inf->priv->notify_port);
1402 MACH_CHECK_ERROR (kret);
1404 /* Deallocate saved exception ports. */
1405 darwin_deallocate_exception_ports (inf->priv);
1407 /* Deallocate task port. */
1408 kret = mach_port_deallocate (gdb_task, inf->priv->task);
1409 MACH_CHECK_ERROR (kret);
1414 inf_child_mourn_inferior (ops);
1418 darwin_reply_to_all_pending_messages (struct inferior *inf)
1424 VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
1427 if (t->msg_state == DARWIN_MESSAGE)
1428 darwin_resume_thread (inf, t, 0, 0);
1433 darwin_stop_inferior (struct inferior *inf)
1435 struct target_waitstatus wstatus;
1441 gdb_assert (inf != NULL);
1443 darwin_suspend_inferior (inf);
1445 darwin_reply_to_all_pending_messages (inf);
1447 if (inf->priv->no_ptrace)
1450 res = kill (inf->pid, SIGSTOP);
1452 warning (_("cannot kill: %s"), safe_strerror (errno));
1454 /* Wait until the process is really stopped. */
1457 ptid = darwin_wait (inferior_ptid, &wstatus);
1458 if (wstatus.kind == TARGET_WAITKIND_STOPPED
1459 && wstatus.value.sig == GDB_SIGNAL_STOP)
1464 static kern_return_t
1465 darwin_save_exception_ports (darwin_inferior *inf)
1469 inf->exception_info.count =
1470 sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1472 kret = task_get_exception_ports
1473 (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1474 &inf->exception_info.count, inf->exception_info.ports,
1475 inf->exception_info.behaviors, inf->exception_info.flavors);
1479 static kern_return_t
1480 darwin_restore_exception_ports (darwin_inferior *inf)
1485 for (i = 0; i < inf->exception_info.count; i++)
1487 kret = task_set_exception_ports
1488 (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1489 inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1490 if (kret != KERN_SUCCESS)
1494 return KERN_SUCCESS;
1497 /* Deallocate saved exception ports. */
1500 darwin_deallocate_exception_ports (darwin_inferior *inf)
1505 for (i = 0; i < inf->exception_info.count; i++)
1507 kret = mach_port_deallocate (gdb_task, inf->exception_info.ports[i]);
1508 MACH_CHECK_ERROR (kret);
1510 inf->exception_info.count = 0;
1514 darwin_setup_exceptions (struct inferior *inf)
1518 exception_mask_t mask;
1520 kret = darwin_save_exception_ports (inf->priv);
1521 if (kret != KERN_SUCCESS)
1522 error (_("Unable to save exception ports, task_get_exception_ports"
1526 /* Set exception port. */
1527 if (enable_mach_exceptions)
1528 mask = EXC_MASK_ALL;
1530 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1531 kret = task_set_exception_ports (inf->priv->task, mask, darwin_ex_port,
1532 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1533 if (kret != KERN_SUCCESS)
1534 error (_("Unable to set exception ports, task_set_exception_ports"
1540 darwin_kill_inferior (struct target_ops *ops)
1542 struct inferior *inf = current_inferior ();
1543 struct target_waitstatus wstatus;
1549 if (ptid_equal (inferior_ptid, null_ptid))
1552 gdb_assert (inf != NULL);
1554 kret = darwin_restore_exception_ports (inf->priv);
1555 MACH_CHECK_ERROR (kret);
1557 darwin_reply_to_all_pending_messages (inf);
1559 res = kill (inf->pid, 9);
1563 darwin_resume_inferior (inf);
1565 ptid = darwin_wait (inferior_ptid, &wstatus);
1567 else if (errno != ESRCH)
1568 warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
1569 inf->pid, safe_strerror (errno));
1571 target_mourn_inferior (inferior_ptid);
1575 darwin_setup_request_notification (struct inferior *inf)
1578 mach_port_t prev_not;
1580 kret = mach_port_request_notification (gdb_task, inf->priv->task,
1581 MACH_NOTIFY_DEAD_NAME, 0,
1582 inf->priv->notify_port,
1583 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1585 if (kret != KERN_SUCCESS)
1586 error (_("Termination notification request failed, "
1587 "mach_port_request_notification\n"
1590 if (prev_not != MACH_PORT_NULL)
1592 /* This is unexpected, as there should not be any previously
1593 registered notification request. But this is not a fatal
1594 issue, so just emit a warning. */
1596 A task termination request was registered before the debugger registered\n\
1597 its own. This is unexpected, but should otherwise not have any actual\n\
1598 impact on the debugging session."));
1603 darwin_attach_pid (struct inferior *inf)
1606 mach_port_t prev_port;
1608 mach_port_t prev_not;
1609 exception_mask_t mask;
1611 inf->priv = XCNEW (darwin_inferior);
1613 kret = task_for_pid (gdb_task, inf->pid, &inf->priv->task);
1614 if (kret != KERN_SUCCESS)
1618 if (!inf->attach_flag)
1621 waitpid (inf->pid, &status, 0);
1624 error (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
1625 " (please check gdb is codesigned - see taskgated(8))"),
1626 inf->pid, mach_error_string (kret), (unsigned long) kret);
1629 inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1630 inf->priv->task, inf->pid);
1632 if (darwin_ex_port == MACH_PORT_NULL)
1634 /* Create a port to get exceptions. */
1635 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1637 if (kret != KERN_SUCCESS)
1638 error (_("Unable to create exception port, mach_port_allocate "
1642 kret = mach_port_insert_right (gdb_task, darwin_ex_port, darwin_ex_port,
1643 MACH_MSG_TYPE_MAKE_SEND);
1644 if (kret != KERN_SUCCESS)
1645 error (_("Unable to create exception port, mach_port_insert_right "
1649 /* Create a port set and put ex_port in it. */
1650 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1652 if (kret != KERN_SUCCESS)
1653 error (_("Unable to create port set, mach_port_allocate "
1657 kret = mach_port_move_member (gdb_task, darwin_ex_port, darwin_port_set);
1658 if (kret != KERN_SUCCESS)
1659 error (_("Unable to move exception port into new port set, "
1660 "mach_port_move_member\n"
1665 /* Create a port to be notified when the child task terminates. */
1666 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1667 &inf->priv->notify_port);
1668 if (kret != KERN_SUCCESS)
1669 error (_("Unable to create notification port, mach_port_allocate "
1673 kret = mach_port_move_member (gdb_task,
1674 inf->priv->notify_port, darwin_port_set);
1675 if (kret != KERN_SUCCESS)
1676 error (_("Unable to move notification port into new port set, "
1677 "mach_port_move_member\n"
1681 darwin_setup_request_notification (inf);
1683 darwin_setup_exceptions (inf);
1685 if (!target_is_pushed (darwin_ops))
1686 push_target (darwin_ops);
1689 /* Get the thread_info object corresponding to this private_thread_info. */
1691 static struct thread_info *
1692 thread_info_from_private_thread_info (private_thread_info *pti)
1694 struct thread_info *it;
1698 if (it->priv->gdb_port == pti->gdb_port)
1702 gdb_assert (it != NULL);
1708 darwin_init_thread_list (struct inferior *inf)
1710 darwin_check_new_threads (inf);
1712 gdb_assert (inf->priv->threads != NULL);
1713 gdb_assert (VEC_length (darwin_thread_t, inf->priv->threads) > 0);
1715 private_thread_info *first_pti
1716 = VEC_index (darwin_thread_t, inf->priv->threads, 0);
1717 struct thread_info *first_thread
1718 = thread_info_from_private_thread_info (first_pti);
1720 inferior_ptid = first_thread->ptid;
1723 /* The child must synchronize with gdb: gdb must set the exception port
1724 before the child call PTRACE_SIGEXC. We use a pipe to achieve this.
1725 FIXME: is there a lighter way ? */
1726 static int ptrace_fds[2];
1729 darwin_ptrace_me (void)
1734 /* Close write end point. */
1735 if (close (ptrace_fds[1]) < 0)
1736 trace_start_error_with_name ("close");
1738 /* Wait until gdb is ready. */
1739 res = read (ptrace_fds[0], &c, 1);
1741 trace_start_error (_("unable to read from pipe, read returned: %d"), res);
1743 if (close (ptrace_fds[0]) < 0)
1744 trace_start_error_with_name ("close");
1746 /* Get rid of privileges. */
1747 if (setegid (getgid ()) < 0)
1748 trace_start_error_with_name ("setegid");
1751 if (PTRACE (PT_TRACE_ME, 0, 0, 0) < 0)
1752 trace_start_error_with_name ("PTRACE");
1754 /* Redirect signals to exception port. */
1755 if (PTRACE (PT_SIGEXC, 0, 0, 0) < 0)
1756 trace_start_error_with_name ("PTRACE");
1759 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2). */
1761 darwin_pre_ptrace (void)
1763 if (pipe (ptrace_fds) != 0)
1767 error (_("unable to create a pipe: %s"), safe_strerror (errno));
1770 mark_fd_no_cloexec (ptrace_fds[0]);
1771 mark_fd_no_cloexec (ptrace_fds[1]);
1775 darwin_ptrace_him (int pid)
1779 mach_port_t prev_port;
1781 struct inferior *inf = current_inferior ();
1783 darwin_attach_pid (inf);
1785 /* Let's the child run. */
1786 close (ptrace_fds[0]);
1787 close (ptrace_fds[1]);
1789 unmark_fd_no_cloexec (ptrace_fds[0]);
1790 unmark_fd_no_cloexec (ptrace_fds[1]);
1792 darwin_init_thread_list (inf);
1794 gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
1798 darwin_execvp (const char *file, char * const argv[], char * const env[])
1800 posix_spawnattr_t attr;
1804 res = posix_spawnattr_init (&attr);
1808 (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
1812 /* Do like execve: replace the image. */
1813 ps_flags = POSIX_SPAWN_SETEXEC;
1815 /* Disable ASLR. The constant doesn't look to be available outside the
1816 kernel include files. */
1817 #ifndef _POSIX_SPAWN_DISABLE_ASLR
1818 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
1820 ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
1821 res = posix_spawnattr_setflags (&attr, ps_flags);
1824 fprintf_unfiltered (gdb_stderr, "Cannot set posix_spawn flags\n");
1828 posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
1832 darwin_create_inferior (struct target_ops *ops,
1833 const char *exec_file,
1834 const std::string &allargs,
1835 char **env, int from_tty)
1837 /* Do the hard work. */
1838 fork_inferior (exec_file, allargs, env, darwin_ptrace_me,
1839 darwin_ptrace_him, darwin_pre_ptrace, NULL,
1844 /* Set things up such that the next call to darwin_wait will immediately
1845 return a fake stop event for inferior INF.
1847 This assumes that the inferior's thread list has been initialized,
1848 as it will suspend the inferior's first thread. */
1851 darwin_setup_fake_stop_event (struct inferior *inf)
1853 darwin_thread_t *thread;
1856 gdb_assert (darwin_inf_fake_stop == NULL);
1857 darwin_inf_fake_stop = inf;
1859 /* When detecting a fake pending stop event, darwin_wait returns
1860 an event saying that the first thread is in a DARWIN_STOPPED
1861 state. To make that accurate, we need to suspend that thread
1862 as well. Otherwise, we'll try resuming it when resuming the
1863 inferior, and get a warning because the thread's suspend count
1864 is already zero, making the resume request useless. */
1865 thread = VEC_index (darwin_thread_t, inf->priv->threads, 0);
1866 kret = thread_suspend (thread->gdb_port);
1867 MACH_CHECK_ERROR (kret);
1870 /* Attach to process PID, then initialize for debugging it
1871 and wait for the trace-trap that results from attaching. */
1873 darwin_attach (struct target_ops *ops, const char *args, int from_tty)
1879 struct inferior *inf;
1882 pid = parse_pid_to_attach (args);
1884 if (pid == getpid ()) /* Trying to masturbate? */
1885 error (_("I refuse to debug myself!"));
1889 char *exec_file = get_exec_file (0);
1892 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
1893 target_pid_to_str (pid_to_ptid (pid)));
1895 printf_unfiltered (_("Attaching to %s\n"),
1896 target_pid_to_str (pid_to_ptid (pid)));
1898 gdb_flush (gdb_stdout);
1901 if (pid == 0 || kill (pid, 0) < 0)
1902 error (_("Can't attach to process %d: %s (%d)"),
1903 pid, safe_strerror (errno), errno);
1905 inferior_ptid = pid_to_ptid (pid);
1906 inf = current_inferior ();
1907 inferior_appeared (inf, pid);
1908 inf->attach_flag = 1;
1910 darwin_attach_pid (inf);
1912 darwin_suspend_inferior (inf);
1914 darwin_init_thread_list (inf);
1916 darwin_check_osabi (inf->priv, ptid_get_tid (inferior_ptid));
1918 darwin_setup_fake_stop_event (inf);
1920 inf->priv->no_ptrace = 1;
1923 /* Take a program previously attached to and detaches it.
1924 The program resumes execution and will no longer stop
1925 on signals, etc. We'd better not have left any breakpoints
1926 in the program or it'll die when it hits one. For this
1927 to work, it may be necessary for the process to have been
1928 previously attached. It *might* work if the program was
1929 started via fork. */
1931 darwin_detach (struct target_ops *ops, const char *args, int from_tty)
1933 pid_t pid = ptid_get_pid (inferior_ptid);
1934 struct inferior *inf = current_inferior ();
1938 /* Display message. */
1939 target_announce_detach (from_tty);
1941 /* If ptrace() is in use, stop the process. */
1942 if (!inf->priv->no_ptrace)
1943 darwin_stop_inferior (inf);
1945 kret = darwin_restore_exception_ports (inf->priv);
1946 MACH_CHECK_ERROR (kret);
1948 if (!inf->priv->no_ptrace)
1950 res = PTRACE (PT_DETACH, inf->pid, 0, 0);
1952 printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
1953 inf->pid, safe_strerror (errno), errno);
1956 darwin_reply_to_all_pending_messages (inf);
1958 /* When using ptrace, we have just performed a PT_DETACH, which
1959 resumes the inferior. On the other hand, when we are not using
1960 ptrace, we need to resume its execution ourselves. */
1961 if (inf->priv->no_ptrace)
1962 darwin_resume_inferior (inf);
1964 darwin_mourn_inferior (ops);
1968 darwin_files_info (struct target_ops *ops)
1973 darwin_pid_to_str (struct target_ops *ops, ptid_t ptid)
1975 static char buf[80];
1976 long tid = ptid_get_tid (ptid);
1980 snprintf (buf, sizeof (buf), _("Thread 0x%lx of process %u"),
1981 tid, ptid_get_pid (ptid));
1985 return normal_pid_to_str (ptid);
1989 darwin_thread_alive (struct target_ops *ops, ptid_t ptid)
1994 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
1995 copy it to RDADDR in gdb's address space.
1996 If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
1997 to ADDR in inferior task's address space.
1998 Return 0 on failure; number of bytes read / writen otherwise. */
2001 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
2002 gdb_byte *rdaddr, const gdb_byte *wraddr,
2006 mach_vm_size_t res_length = 0;
2008 mach_msg_type_number_t copy_count;
2009 mach_vm_size_t remaining_length;
2010 mach_vm_address_t region_address;
2011 mach_vm_size_t region_length;
2013 inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
2014 task, core_addr_to_string (addr), pulongest (length));
2019 mach_vm_size_t count;
2021 /* According to target.h(to_xfer_partial), one and only one may be
2023 gdb_assert (wraddr == NULL);
2025 kret = mach_vm_read_overwrite (task, addr, length,
2026 (mach_vm_address_t) rdaddr, &count);
2027 if (kret != KERN_SUCCESS)
2030 (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
2031 core_addr_to_string (addr), mach_error_string (kret));
2038 gdb_assert (wraddr != NULL);
2042 mach_vm_address_t offset = addr & (mach_page_size - 1);
2043 mach_vm_address_t region_address = (mach_vm_address_t) (addr - offset);
2044 mach_vm_size_t aligned_length =
2045 (mach_vm_size_t) PAGE_ROUND (offset + length);
2046 vm_region_submap_short_info_data_64_t info;
2047 mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
2048 natural_t region_depth = 1000;
2049 mach_vm_address_t region_start = region_address;
2050 mach_vm_size_t region_length;
2051 mach_vm_size_t write_length;
2053 /* Read page protection. */
2054 kret = mach_vm_region_recurse
2055 (task, ®ion_start, ®ion_length, ®ion_depth,
2056 (vm_region_recurse_info_t) &info, &count);
2058 if (kret != KERN_SUCCESS)
2060 inferior_debug (1, _("darwin_read_write_inferior: "
2061 "mach_vm_region_recurse failed at %s: %s\n"),
2062 core_addr_to_string (region_address),
2063 mach_error_string (kret));
2068 (9, _("darwin_read_write_inferior: "
2069 "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
2070 core_addr_to_string (region_address),
2071 core_addr_to_string (region_start),
2072 core_addr_to_string (region_length));
2074 /* Check for holes in memory. */
2075 if (region_start > region_address)
2077 warning (_("No memory at %s (vs %s+0x%x). Nothing written"),
2078 core_addr_to_string (region_address),
2079 core_addr_to_string (region_start),
2080 (unsigned)region_length);
2084 /* Adjust the length. */
2085 region_length -= (region_address - region_start);
2086 if (region_length > aligned_length)
2087 region_length = aligned_length;
2089 /* Make the pages RW. */
2090 if (!(info.protection & VM_PROT_WRITE))
2092 vm_prot_t prot = VM_PROT_READ | VM_PROT_WRITE;
2094 kret = mach_vm_protect (task, region_address, region_length,
2096 if (kret != KERN_SUCCESS)
2098 prot |= VM_PROT_COPY;
2099 kret = mach_vm_protect (task, region_address, region_length,
2102 if (kret != KERN_SUCCESS)
2104 warning (_("darwin_read_write_inferior: "
2105 "mach_vm_protect failed at %s "
2106 "(len=0x%lx, prot=0x%x): %s"),
2107 core_addr_to_string (region_address),
2108 (unsigned long) region_length, (unsigned) prot,
2109 mach_error_string (kret));
2114 if (offset + length > region_length)
2115 write_length = region_length - offset;
2117 write_length = length;
2120 kret = mach_vm_write (task, addr, (vm_offset_t) wraddr, write_length);
2121 if (kret != KERN_SUCCESS)
2123 warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
2124 mach_error_string (kret));
2128 /* Restore page rights. */
2129 if (!(info.protection & VM_PROT_WRITE))
2131 kret = mach_vm_protect (task, region_address, region_length,
2132 FALSE, info.protection);
2133 if (kret != KERN_SUCCESS)
2135 warning (_("darwin_read_write_inferior: "
2136 "mach_vm_protect restore failed at %s "
2138 core_addr_to_string (region_address),
2139 (unsigned long) region_length,
2140 mach_error_string (kret));
2144 addr += write_length;
2145 wraddr += write_length;
2146 res_length += write_length;
2147 length -= write_length;
2153 /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
2154 to RDADDR (in big endian).
2155 Return 0 on failure; number of bytes read / written otherwise. */
2157 #ifdef TASK_DYLD_INFO_COUNT
2158 /* This is not available in Darwin 9. */
2159 static enum target_xfer_status
2160 darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
2161 ULONGEST length, ULONGEST *xfered_len)
2163 struct task_dyld_info task_dyld_info;
2164 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
2165 int sz = TASK_DYLD_INFO_COUNT * sizeof (natural_t);
2168 if (addr != 0 || length > sizeof (mach_vm_address_t))
2169 return TARGET_XFER_EOF;
2171 kret = task_info (task, TASK_DYLD_INFO,
2172 (task_info_t) &task_dyld_info, &count);
2173 MACH_CHECK_ERROR (kret);
2174 if (kret != KERN_SUCCESS)
2175 return TARGET_XFER_E_IO;
2177 store_unsigned_integer (rdaddr, length, BFD_ENDIAN_BIG,
2178 task_dyld_info.all_image_info_addr);
2179 *xfered_len = (ULONGEST) length;
2180 return TARGET_XFER_OK;
2186 static enum target_xfer_status
2187 darwin_xfer_partial (struct target_ops *ops,
2188 enum target_object object, const char *annex,
2189 gdb_byte *readbuf, const gdb_byte *writebuf,
2190 ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
2192 struct inferior *inf = current_inferior ();
2195 (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
2196 core_addr_to_string (offset), pulongest (len),
2197 host_address_to_string (readbuf), host_address_to_string (writebuf),
2202 case TARGET_OBJECT_MEMORY:
2204 int l = darwin_read_write_inferior (inf->priv->task, offset,
2205 readbuf, writebuf, len);
2208 return TARGET_XFER_EOF;
2212 *xfered_len = (ULONGEST) l;
2213 return TARGET_XFER_OK;
2216 #ifdef TASK_DYLD_INFO_COUNT
2217 case TARGET_OBJECT_DARWIN_DYLD_INFO:
2218 if (writebuf != NULL || readbuf == NULL)
2220 /* Support only read. */
2221 return TARGET_XFER_E_IO;
2223 return darwin_read_dyld_info (inf->priv->task, offset, readbuf, len,
2227 return TARGET_XFER_E_IO;
2233 set_enable_mach_exceptions (char *args, int from_tty,
2234 struct cmd_list_element *c)
2236 if (!ptid_equal (inferior_ptid, null_ptid))
2238 struct inferior *inf = current_inferior ();
2239 exception_mask_t mask;
2242 if (enable_mach_exceptions)
2243 mask = EXC_MASK_ALL;
2246 darwin_restore_exception_ports (inf->priv);
2247 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
2249 kret = task_set_exception_ports (inf->priv->task, mask, darwin_ex_port,
2250 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
2251 MACH_CHECK_ERROR (kret);
2256 darwin_pid_to_exec_file (struct target_ops *self, int pid)
2258 static char path[PATH_MAX];
2261 res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
2269 darwin_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
2274 struct inferior *inf = current_inferior ();
2276 mach_port_name_array_t names;
2277 mach_msg_type_number_t names_count;
2278 mach_port_type_array_t types;
2279 mach_msg_type_number_t types_count;
2282 /* First linear search. */
2284 VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
2286 if (t->inf_port == lwp)
2287 return ptid_build (ptid_get_pid (inferior_ptid), 0, t->gdb_port);
2289 /* Maybe the port was never extract. Do it now. */
2291 /* First get inferior port names. */
2292 kret = mach_port_names (inf->priv->task, &names, &names_count, &types,
2294 MACH_CHECK_ERROR (kret);
2295 if (kret != KERN_SUCCESS)
2298 /* For each name, copy the right in the gdb space and then compare with
2299 our view of the inferior threads. We don't forget to deallocate the
2301 for (i = 0; i < names_count; i++)
2303 mach_port_t local_name;
2304 mach_msg_type_name_t local_type;
2306 /* We just need to know the corresponding name in gdb name space.
2307 So extract and deallocate the right. */
2308 kret = mach_port_extract_right (inf->priv->task, names[i],
2309 MACH_MSG_TYPE_COPY_SEND,
2310 &local_name, &local_type);
2311 if (kret != KERN_SUCCESS)
2313 mach_port_deallocate (gdb_task, local_name);
2316 VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
2318 if (t->gdb_port == local_name)
2320 t->inf_port = names[i];
2321 if (names[i] == lwp)
2326 vm_deallocate (gdb_task, (vm_address_t) names,
2327 names_count * sizeof (mach_port_t));
2330 return ptid_build (ptid_get_pid (inferior_ptid), 0, res);
2336 darwin_supports_multi_process (struct target_ops *self)
2342 _initialize_darwin_inferior (void)
2346 gdb_task = mach_task_self ();
2347 darwin_host_self = mach_host_self ();
2349 /* Read page size. */
2350 kret = host_page_size (darwin_host_self, &mach_page_size);
2351 if (kret != KERN_SUCCESS)
2353 mach_page_size = 0x1000;
2354 MACH_CHECK_ERROR (kret);
2357 darwin_ops = inf_child_target ();
2359 darwin_ops->to_create_inferior = darwin_create_inferior;
2360 darwin_ops->to_attach = darwin_attach;
2361 darwin_ops->to_attach_no_wait = 0;
2362 darwin_ops->to_detach = darwin_detach;
2363 darwin_ops->to_files_info = darwin_files_info;
2364 darwin_ops->to_wait = darwin_wait_to;
2365 darwin_ops->to_mourn_inferior = darwin_mourn_inferior;
2366 darwin_ops->to_kill = darwin_kill_inferior;
2367 darwin_ops->to_interrupt = darwin_interrupt;
2368 darwin_ops->to_resume = darwin_resume_to;
2369 darwin_ops->to_thread_alive = darwin_thread_alive;
2370 darwin_ops->to_pid_to_str = darwin_pid_to_str;
2371 darwin_ops->to_pid_to_exec_file = darwin_pid_to_exec_file;
2372 darwin_ops->to_load = NULL;
2373 darwin_ops->to_xfer_partial = darwin_xfer_partial;
2374 darwin_ops->to_supports_multi_process = darwin_supports_multi_process;
2375 darwin_ops->to_get_ada_task_ptid = darwin_get_ada_task_ptid;
2377 darwin_complete_target (darwin_ops);
2379 add_target (darwin_ops);
2381 inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"),
2382 (unsigned long) mach_task_self (), getpid ());
2384 add_setshow_zuinteger_cmd ("darwin", class_obscure,
2385 &darwin_debug_flag, _("\
2386 Set if printing inferior communication debugging statements."), _("\
2387 Show if printing inferior communication debugging statements."), NULL,
2389 &setdebuglist, &showdebuglist);
2391 add_setshow_boolean_cmd ("mach-exceptions", class_support,
2392 &enable_mach_exceptions, _("\
2393 Set if mach exceptions are caught."), _("\
2394 Show if mach exceptions are caught."), _("\
2395 When this mode is on, all low level exceptions are reported before being\n\
2396 reported by the kernel."),
2397 &set_enable_mach_exceptions, NULL,
2398 &setlist, &showlist);