Tests for validate symbol file using build-id.
[gdb/archer.git] / gdb / darwin-nat.c
blob1344101c7cb70ec3dda18031aa0bf9ee99bd6765
1 /* Darwin support for GDB, the GNU debugger.
2 Copyright (C) 2008-2013 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/>.
22 #include "defs.h"
23 #include "top.h"
24 #include "inferior.h"
25 #include "target.h"
26 #include "symfile.h"
27 #include "symtab.h"
28 #include "objfiles.h"
29 #include "gdb.h"
30 #include "gdbcmd.h"
31 #include "gdbcore.h"
32 #include "gdbthread.h"
33 #include "regcache.h"
34 #include "event-top.h"
35 #include "inf-loop.h"
36 #include "gdb_stat.h"
37 #include "exceptions.h"
38 #include "inf-child.h"
39 #include "value.h"
40 #include "arch-utils.h"
41 #include "bfd.h"
42 #include "bfd/mach-o.h"
44 #include <sys/ptrace.h>
45 #include <sys/signal.h>
46 #include <machine/setjmp.h>
47 #include <sys/types.h>
48 #include <unistd.h>
49 #include <signal.h>
50 #include <string.h>
51 #include <ctype.h>
52 #include <sys/param.h>
53 #include <sys/sysctl.h>
54 #include <sys/proc.h>
55 #include <libproc.h>
56 #include <sys/syscall.h>
57 #include <spawn.h>
59 #include <mach/mach_error.h>
60 #include <mach/mach_vm.h>
61 #include <mach/mach_init.h>
62 #include <mach/vm_map.h>
63 #include <mach/task.h>
64 #include <mach/mach_port.h>
65 #include <mach/thread_act.h>
66 #include <mach/port.h>
68 #include "darwin-nat.h"
70 /* Quick overview.
71 Darwin kernel is Mach + BSD derived kernel. Note that they share the
72 same memory space and are linked together (ie there is no micro-kernel).
74 Although ptrace(2) is available on Darwin, it is not complete. We have
75 to use Mach calls to read and write memory and to modify registers. We
76 also use Mach to get inferior faults. As we cannot use select(2) or
77 signals with Mach port (the Mach communication channel), signals are
78 reported to gdb as an exception. Furthermore we detect death of the
79 inferior through a Mach notification message. This way we only wait
80 on Mach ports.
82 Some Mach documentation is available for Apple xnu source package or
83 from the web. */
86 #define PTRACE(CMD, PID, ADDR, SIG) \
87 darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
89 extern boolean_t exc_server (mach_msg_header_t *in, mach_msg_header_t *out);
91 static void darwin_stop (ptid_t);
93 static void darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
94 enum gdb_signal signal);
95 static void darwin_resume (ptid_t ptid, int step,
96 enum gdb_signal signal);
98 static ptid_t darwin_wait_to (struct target_ops *ops, ptid_t ptid,
99 struct target_waitstatus *status, int options);
100 static ptid_t darwin_wait (ptid_t ptid, struct target_waitstatus *status);
102 static void darwin_mourn_inferior (struct target_ops *ops);
104 static void darwin_kill_inferior (struct target_ops *ops);
106 static void darwin_ptrace_me (void);
108 static void darwin_ptrace_him (int pid);
110 static void darwin_create_inferior (struct target_ops *ops, char *exec_file,
111 char *allargs, char **env, int from_tty);
113 static void darwin_files_info (struct target_ops *ops);
115 static char *darwin_pid_to_str (struct target_ops *ops, ptid_t tpid);
117 static int darwin_thread_alive (struct target_ops *ops, ptid_t tpid);
119 /* Target operations for Darwin. */
120 static struct target_ops *darwin_ops;
122 /* Task identifier of gdb. */
123 static task_t gdb_task;
125 /* A copy of mach_host_self (). */
126 mach_port_t darwin_host_self;
128 /* Exception port. */
129 mach_port_t darwin_ex_port;
131 /* Port set. */
132 mach_port_t darwin_port_set;
134 /* Page size. */
135 static vm_size_t mach_page_size;
137 /* If Set, catch all mach exceptions (before they are converted to signals
138 by the kernel). */
139 static int enable_mach_exceptions;
141 /* Inferior that should report a fake stop event. */
142 static struct inferior *darwin_inf_fake_stop;
144 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
145 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
147 /* This controls output of inferior debugging. */
148 static unsigned int darwin_debug_flag = 0;
150 /* Create a __TEXT __info_plist section in the executable so that gdb could
151 be signed. This is required to get an authorization for task_for_pid.
153 Once gdb is built, you can either:
154 * make it setgid procmod
155 * or codesign it with any system-trusted signing authority.
156 See taskgated(8) for details. */
157 static const unsigned char info_plist[]
158 __attribute__ ((section ("__TEXT,__info_plist"),used)) =
159 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
160 "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
161 " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
162 "<plist version=\"1.0\">\n"
163 "<dict>\n"
164 " <key>CFBundleIdentifier</key>\n"
165 " <string>org.gnu.gdb</string>\n"
166 " <key>CFBundleName</key>\n"
167 " <string>gdb</string>\n"
168 " <key>CFBundleVersion</key>\n"
169 " <string>1.0</string>\n"
170 " <key>SecTaskAccess</key>\n"
171 " <array>\n"
172 " <string>allowed</string>\n"
173 " <string>debug</string>\n"
174 " </array>\n"
175 "</dict>\n"
176 "</plist>\n";
178 static void
179 inferior_debug (int level, const char *fmt, ...)
181 va_list ap;
183 if (darwin_debug_flag < level)
184 return;
186 va_start (ap, fmt);
187 printf_unfiltered (_("[%d inferior]: "), getpid ());
188 vprintf_unfiltered (fmt, ap);
189 va_end (ap);
192 void
193 mach_check_error (kern_return_t ret, const char *file,
194 unsigned int line, const char *func)
196 if (ret == KERN_SUCCESS)
197 return;
198 if (func == NULL)
199 func = _("[UNKNOWN]");
201 warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
202 file, line, func, mach_error_string (ret), (unsigned long) ret);
205 static const char *
206 unparse_exception_type (unsigned int i)
208 static char unknown_exception_buf[32];
210 switch (i)
212 case EXC_BAD_ACCESS:
213 return "EXC_BAD_ACCESS";
214 case EXC_BAD_INSTRUCTION:
215 return "EXC_BAD_INSTRUCTION";
216 case EXC_ARITHMETIC:
217 return "EXC_ARITHMETIC";
218 case EXC_EMULATION:
219 return "EXC_EMULATION";
220 case EXC_SOFTWARE:
221 return "EXC_SOFTWARE";
222 case EXC_BREAKPOINT:
223 return "EXC_BREAKPOINT";
224 case EXC_SYSCALL:
225 return "EXC_SYSCALL";
226 case EXC_MACH_SYSCALL:
227 return "EXC_MACH_SYSCALL";
228 case EXC_RPC_ALERT:
229 return "EXC_RPC_ALERT";
230 case EXC_CRASH:
231 return "EXC_CRASH";
232 default:
233 snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
234 return unknown_exception_buf;
238 /* Set errno to zero, and then call ptrace with the given arguments.
239 If inferior debugging traces are on, then also print a debug
240 trace.
242 The returned value is the same as the value returned by ptrace,
243 except in the case where that value is -1 but errno is zero.
244 This case is documented to be a non-error situation, so we
245 return zero in that case. */
247 static int
248 darwin_ptrace (const char *name,
249 int request, int pid, PTRACE_TYPE_ARG3 arg3, int arg4)
251 int ret;
253 errno = 0;
254 ret = ptrace (request, pid, (caddr_t) arg3, arg4);
255 if (ret == -1 && errno == 0)
256 ret = 0;
258 inferior_debug (4, _("ptrace (%s, %d, 0x%x, %d): %d (%s)\n"),
259 name, pid, arg3, arg4, ret,
260 (ret != 0) ? safe_strerror (errno) : _("no error"));
261 return ret;
264 static int
265 cmp_thread_t (const void *l, const void *r)
267 thread_t tl = *(const thread_t *)l;
268 thread_t tr = *(const thread_t *)r;
269 return (int)(tl - tr);
272 static void
273 darwin_check_new_threads (struct inferior *inf)
275 kern_return_t kret;
276 unsigned int i;
277 thread_array_t thread_list;
278 unsigned int new_nbr;
279 unsigned int old_nbr;
280 unsigned int new_ix, old_ix;
281 darwin_inferior *darwin_inf = inf->private;
282 VEC (darwin_thread_t) *thread_vec;
284 /* Get list of threads. */
285 kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
286 MACH_CHECK_ERROR (kret);
287 if (kret != KERN_SUCCESS)
288 return;
290 /* Sort the list. */
291 if (new_nbr > 1)
292 qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
294 if (darwin_inf->threads)
295 old_nbr = VEC_length (darwin_thread_t, darwin_inf->threads);
296 else
297 old_nbr = 0;
299 /* Quick check for no changes. */
300 if (old_nbr == new_nbr)
302 for (i = 0; i < new_nbr; i++)
303 if (thread_list[i]
304 != VEC_index (darwin_thread_t, darwin_inf->threads, i)->gdb_port)
305 break;
306 if (i == new_nbr)
308 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
309 new_nbr * sizeof (int));
310 MACH_CHECK_ERROR (kret);
311 return;
315 thread_vec = VEC_alloc (darwin_thread_t, new_nbr);
317 for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
319 thread_t new_id = (new_ix < new_nbr) ?
320 thread_list[new_ix] : THREAD_NULL;
321 darwin_thread_t *old = (old_ix < old_nbr) ?
322 VEC_index (darwin_thread_t, darwin_inf->threads, old_ix) : NULL;
323 thread_t old_id = old ? old->gdb_port : THREAD_NULL;
325 inferior_debug
326 (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:%x old_id:%x\n"),
327 new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
329 if (old_id == new_id)
331 /* Thread still exist. */
332 VEC_safe_push (darwin_thread_t, thread_vec, old);
333 new_ix++;
334 old_ix++;
336 kret = mach_port_deallocate (gdb_task, old_id);
337 MACH_CHECK_ERROR (kret);
338 continue;
340 if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
342 /* Ignore dead ports.
343 In some weird cases, we might get dead ports. They should
344 correspond to dead thread so they could safely be ignored. */
345 new_ix++;
346 continue;
348 if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
350 /* A thread was created. */
351 struct thread_info *tp;
352 struct private_thread_info *pti;
354 pti = XZALLOC (struct private_thread_info);
355 pti->gdb_port = new_id;
356 pti->msg_state = DARWIN_RUNNING;
358 /* Add a new thread unless this is the first one ever met. */
359 if (!(old_nbr == 0 && new_ix == 0))
360 tp = add_thread_with_info (ptid_build (inf->pid, 0, new_id), pti);
361 else
363 tp = find_thread_ptid (ptid_build (inf->pid, 0, 0));
364 gdb_assert (tp);
365 tp->private = pti;
367 VEC_safe_push (darwin_thread_t, thread_vec, pti);
368 new_ix++;
369 continue;
371 if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
373 /* A thread was removed. */
374 delete_thread (ptid_build (inf->pid, 0, old_id));
375 kret = mach_port_deallocate (gdb_task, old_id);
376 MACH_CHECK_ERROR (kret);
377 old_ix++;
378 continue;
380 gdb_assert_not_reached ("unexpected thread case");
383 if (darwin_inf->threads)
384 VEC_free (darwin_thread_t, darwin_inf->threads);
385 darwin_inf->threads = thread_vec;
387 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
388 new_nbr * sizeof (int));
389 MACH_CHECK_ERROR (kret);
392 static int
393 find_inferior_task_it (struct inferior *inf, void *port_ptr)
395 return inf->private->task == *(task_t*)port_ptr;
398 static int
399 find_inferior_notify_it (struct inferior *inf, void *port_ptr)
401 return inf->private->notify_port == *(task_t*)port_ptr;
404 /* Return an inferior by task port. */
405 static struct inferior *
406 darwin_find_inferior_by_task (task_t port)
408 return iterate_over_inferiors (&find_inferior_task_it, &port);
411 /* Return an inferior by notification port. */
412 static struct inferior *
413 darwin_find_inferior_by_notify (mach_port_t port)
415 return iterate_over_inferiors (&find_inferior_notify_it, &port);
418 /* Return a thread by port. */
419 static darwin_thread_t *
420 darwin_find_thread (struct inferior *inf, thread_t thread)
422 darwin_thread_t *t;
423 int k;
425 for (k = 0;
426 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
427 k++)
428 if (t->gdb_port == thread)
429 return t;
430 return NULL;
433 /* Suspend (ie stop) an inferior at Mach level. */
435 static void
436 darwin_suspend_inferior (struct inferior *inf)
438 if (!inf->private->suspended)
440 kern_return_t kret;
442 kret = task_suspend (inf->private->task);
443 MACH_CHECK_ERROR (kret);
445 inf->private->suspended = 1;
449 /* Resume an inferior at Mach level. */
451 static void
452 darwin_resume_inferior (struct inferior *inf)
454 if (inf->private->suspended)
456 kern_return_t kret;
458 kret = task_resume (inf->private->task);
459 MACH_CHECK_ERROR (kret);
461 inf->private->suspended = 0;
465 /* Iterator functions. */
467 static int
468 darwin_suspend_inferior_it (struct inferior *inf, void *arg)
470 darwin_suspend_inferior (inf);
471 darwin_check_new_threads (inf);
472 return 0;
475 static int
476 darwin_resume_inferior_it (struct inferior *inf, void *arg)
478 darwin_resume_inferior (inf);
479 return 0;
482 static void
483 darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
485 printf_unfiltered (_("message header:\n"));
486 printf_unfiltered (_(" bits: 0x%x\n"), hdr->msgh_bits);
487 printf_unfiltered (_(" size: 0x%x\n"), hdr->msgh_size);
488 printf_unfiltered (_(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
489 printf_unfiltered (_(" local-port: 0x%x\n"), hdr->msgh_local_port);
490 printf_unfiltered (_(" reserved: 0x%x\n"), hdr->msgh_reserved);
491 printf_unfiltered (_(" id: 0x%x\n"), hdr->msgh_id);
493 if (disp_body)
495 const unsigned char *data;
496 const unsigned long *ldata;
497 int size;
498 int i;
500 data = (unsigned char *)(hdr + 1);
501 size = hdr->msgh_size - sizeof (mach_msg_header_t);
503 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
505 mach_msg_body_t *bod = (mach_msg_body_t*)data;
506 mach_msg_port_descriptor_t *desc =
507 (mach_msg_port_descriptor_t *)(bod + 1);
508 int k;
509 NDR_record_t *ndr;
510 printf_unfiltered (_("body: descriptor_count=%u\n"),
511 bod->msgh_descriptor_count);
512 data += sizeof (mach_msg_body_t);
513 size -= sizeof (mach_msg_body_t);
514 for (k = 0; k < bod->msgh_descriptor_count; k++)
515 switch (desc[k].type)
517 case MACH_MSG_PORT_DESCRIPTOR:
518 printf_unfiltered
519 (_(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
520 k, desc[k].type, desc[k].name, desc[k].disposition);
521 break;
522 default:
523 printf_unfiltered (_(" descr %d: type=%u\n"),
524 k, desc[k].type);
525 break;
527 data += bod->msgh_descriptor_count
528 * sizeof (mach_msg_port_descriptor_t);
529 size -= bod->msgh_descriptor_count
530 * sizeof (mach_msg_port_descriptor_t);
531 ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
532 printf_unfiltered
533 (_("NDR: mig=%02x if=%02x encod=%02x "
534 "int=%02x char=%02x float=%02x\n"),
535 ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
536 ndr->int_rep, ndr->char_rep, ndr->float_rep);
537 data += sizeof (NDR_record_t);
538 size -= sizeof (NDR_record_t);
541 printf_unfiltered (_(" data:"));
542 ldata = (const unsigned long *)data;
543 for (i = 0; i < size / sizeof (unsigned long); i++)
544 printf_unfiltered (" %08lx", ldata[i]);
545 printf_unfiltered (_("\n"));
549 static int
550 darwin_decode_exception_message (mach_msg_header_t *hdr,
551 struct inferior **pinf,
552 darwin_thread_t **pthread)
554 mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
555 mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
556 NDR_record_t *ndr;
557 integer_t *data;
558 struct inferior *inf;
559 darwin_thread_t *thread;
560 task_t task_port;
561 thread_t thread_port;
562 kern_return_t kret;
563 int i;
565 /* Check message identifier. 2401 is exc. */
566 if (hdr->msgh_id != 2401)
567 return -1;
569 /* Check message header. */
570 if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
571 return -1;
573 /* Check descriptors. */
574 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
575 + sizeof (*ndr) + 2 * sizeof (integer_t))
576 || bod->msgh_descriptor_count != 2
577 || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
578 || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
579 || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
580 || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
581 return -1;
583 /* Check data representation. */
584 ndr = (NDR_record_t *)(desc + 2);
585 if (ndr->mig_vers != NDR_PROTOCOL_2_0
586 || ndr->if_vers != NDR_PROTOCOL_2_0
587 || ndr->mig_encoding != NDR_record.mig_encoding
588 || ndr->int_rep != NDR_record.int_rep
589 || ndr->char_rep != NDR_record.char_rep
590 || ndr->float_rep != NDR_record.float_rep)
591 return -1;
593 /* Ok, the hard work. */
594 data = (integer_t *)(ndr + 1);
596 /* Find process by port. */
597 task_port = desc[1].name;
598 thread_port = desc[0].name;
599 inf = darwin_find_inferior_by_task (task_port);
600 if (inf == NULL)
601 return -1;
602 *pinf = inf;
604 /* Find thread by port. */
605 /* Check for new threads. Do it early so that the port in the exception
606 message can be deallocated. */
607 darwin_check_new_threads (inf);
609 /* We got new rights to the task and the thread. Get rid of them. */
610 kret = mach_port_deallocate (mach_task_self (), task_port);
611 MACH_CHECK_ERROR (kret);
612 kret = mach_port_deallocate (mach_task_self (), thread_port);
613 MACH_CHECK_ERROR (kret);
615 thread = darwin_find_thread (inf, thread_port);
616 if (thread == NULL)
617 return -1;
618 *pthread = thread;
620 /* The thread should be running. However we have observed cases where a thread
621 got a SIGTTIN message after being stopped. */
622 gdb_assert (thread->msg_state != DARWIN_MESSAGE);
624 /* Finish decoding. */
625 thread->event.header = *hdr;
626 thread->event.thread_port = thread_port;
627 thread->event.task_port = task_port;
628 thread->event.ex_type = data[0];
629 thread->event.data_count = data[1];
631 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
632 + sizeof (*ndr) + 2 * sizeof (integer_t)
633 + data[1] * sizeof (integer_t)))
634 return -1;
635 for (i = 0; i < data[1]; i++)
636 thread->event.ex_data[i] = data[2 + i];
638 thread->msg_state = DARWIN_MESSAGE;
640 return 0;
643 static void
644 darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
645 integer_t code)
647 mach_msg_header_t *rh = &reply->Head;
648 rh->msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(hdr->msgh_bits), 0);
649 rh->msgh_remote_port = hdr->msgh_remote_port;
650 rh->msgh_size = (mach_msg_size_t)sizeof(mig_reply_error_t);
651 rh->msgh_local_port = MACH_PORT_NULL;
652 rh->msgh_id = hdr->msgh_id + 100;
654 reply->NDR = NDR_record;
655 reply->RetCode = code;
658 static void
659 darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
661 kern_return_t kret;
662 mig_reply_error_t reply;
664 darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
666 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
667 reply.Head.msgh_size, 0,
668 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
669 MACH_PORT_NULL);
670 MACH_CHECK_ERROR (kret);
672 inf->private->pending_messages--;
675 static void
676 darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
677 int step, int nsignal)
679 kern_return_t kret;
680 int res;
682 inferior_debug
683 (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
684 thread->msg_state, thread->gdb_port, step, nsignal);
686 switch (thread->msg_state)
688 case DARWIN_MESSAGE:
689 if (thread->event.ex_type == EXC_SOFTWARE
690 && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
692 /* Either deliver a new signal or cancel the signal received. */
693 res = PTRACE (PT_THUPDATE, inf->pid,
694 (void *)(uintptr_t)thread->gdb_port, nsignal);
695 if (res < 0)
696 inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
698 else if (nsignal)
700 /* Note: ptrace is allowed only if the process is stopped.
701 Directly send the signal to the thread. */
702 res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
703 inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
704 thread->gdb_port, nsignal, res);
705 thread->signaled = 1;
708 /* Set or reset single step. */
709 if (step != thread->single_step)
711 inferior_debug (4, _("darwin_set_sstep (thread=%x, enable=%d)\n"),
712 thread->gdb_port, step);
713 darwin_set_sstep (thread->gdb_port, step);
714 thread->single_step = step;
717 darwin_send_reply (inf, thread);
718 thread->msg_state = DARWIN_RUNNING;
719 break;
721 case DARWIN_RUNNING:
722 break;
724 case DARWIN_STOPPED:
725 kret = thread_resume (thread->gdb_port);
726 MACH_CHECK_ERROR (kret);
728 thread->msg_state = DARWIN_RUNNING;
729 break;
733 /* Resume all threads of the inferior. */
735 static void
736 darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
738 darwin_thread_t *thread;
739 int k;
741 for (k = 0;
742 VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
743 k++)
744 darwin_resume_thread (inf, thread, step, nsignal);
747 struct resume_inferior_threads_param
749 int step;
750 int nsignal;
753 static int
754 darwin_resume_inferior_threads_it (struct inferior *inf, void *param)
756 int step = ((struct resume_inferior_threads_param *)param)->step;
757 int nsignal = ((struct resume_inferior_threads_param *)param)->nsignal;
759 darwin_resume_inferior_threads (inf, step, nsignal);
761 return 0;
764 /* Suspend all threads of INF. */
766 static void
767 darwin_suspend_inferior_threads (struct inferior *inf)
769 darwin_thread_t *thread;
770 kern_return_t kret;
771 int k;
773 for (k = 0;
774 VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
775 k++)
776 switch (thread->msg_state)
778 case DARWIN_STOPPED:
779 case DARWIN_MESSAGE:
780 break;
781 case DARWIN_RUNNING:
782 kret = thread_suspend (thread->gdb_port);
783 MACH_CHECK_ERROR (kret);
784 thread->msg_state = DARWIN_STOPPED;
785 break;
789 static void
790 darwin_resume (ptid_t ptid, int step, enum gdb_signal signal)
792 struct target_waitstatus status;
793 int pid;
795 kern_return_t kret;
796 int res;
797 int nsignal;
798 struct inferior *inf;
800 inferior_debug
801 (2, _("darwin_resume: pid=%d, tid=0x%x, step=%d, signal=%d\n"),
802 ptid_get_pid (ptid), ptid_get_tid (ptid), step, signal);
804 if (signal == GDB_SIGNAL_0)
805 nsignal = 0;
806 else
807 nsignal = gdb_signal_to_host (signal);
809 /* Don't try to single step all threads. */
810 if (step)
811 ptid = inferior_ptid;
813 /* minus_one_ptid is RESUME_ALL. */
814 if (ptid_equal (ptid, minus_one_ptid))
816 struct resume_inferior_threads_param param;
818 param.nsignal = nsignal;
819 param.step = step;
821 /* Resume threads. */
822 iterate_over_inferiors (darwin_resume_inferior_threads_it, &param);
823 /* Resume tasks. */
824 iterate_over_inferiors (darwin_resume_inferior_it, NULL);
826 else
828 struct inferior *inf = find_inferior_pid (ptid_get_pid (ptid));
829 long tid = ptid_get_tid (ptid);
831 /* Stop the inferior (should be useless). */
832 darwin_suspend_inferior (inf);
834 if (tid == 0)
835 darwin_resume_inferior_threads (inf, step, nsignal);
836 else
838 darwin_thread_t *thread;
840 /* Suspend threads of the task. */
841 darwin_suspend_inferior_threads (inf);
843 /* Resume the selected thread. */
844 thread = darwin_find_thread (inf, tid);
845 gdb_assert (thread);
846 darwin_resume_thread (inf, thread, step, nsignal);
849 /* Resume the task. */
850 darwin_resume_inferior (inf);
854 static void
855 darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
856 enum gdb_signal signal)
858 return darwin_resume (ptid, step, signal);
861 static ptid_t
862 darwin_decode_message (mach_msg_header_t *hdr,
863 darwin_thread_t **pthread,
864 struct inferior **pinf,
865 struct target_waitstatus *status)
867 darwin_thread_t *thread;
868 struct inferior *inf;
870 /* Exception message. */
871 if (hdr->msgh_local_port == darwin_ex_port)
873 int res;
875 /* Decode message. */
876 res = darwin_decode_exception_message (hdr, &inf, &thread);
878 if (res < 0)
880 /* Should not happen... */
881 printf_unfiltered (_("darwin_wait: ill-formatted message (id=%x)\n"),
882 hdr->msgh_id);
883 /* FIXME: send a failure reply? */
884 status->kind = TARGET_WAITKIND_SPURIOUS;
885 return minus_one_ptid;
887 *pinf = inf;
888 *pthread = thread;
889 inf->private->pending_messages++;
891 status->kind = TARGET_WAITKIND_STOPPED;
892 thread->msg_state = DARWIN_MESSAGE;
894 inferior_debug (4, _("darwin_wait: thread=%x, got %s\n"),
895 thread->gdb_port,
896 unparse_exception_type (thread->event.ex_type));
898 switch (thread->event.ex_type)
900 case EXC_BAD_ACCESS:
901 status->value.sig = TARGET_EXC_BAD_ACCESS;
902 break;
903 case EXC_BAD_INSTRUCTION:
904 status->value.sig = TARGET_EXC_BAD_INSTRUCTION;
905 break;
906 case EXC_ARITHMETIC:
907 status->value.sig = TARGET_EXC_ARITHMETIC;
908 break;
909 case EXC_EMULATION:
910 status->value.sig = TARGET_EXC_EMULATION;
911 break;
912 case EXC_SOFTWARE:
913 if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
915 status->value.sig =
916 gdb_signal_from_host (thread->event.ex_data[1]);
917 inferior_debug (5, _(" (signal %d: %s)\n"),
918 thread->event.ex_data[1],
919 gdb_signal_to_name (status->value.sig));
921 /* If the thread is stopped because it has received a signal
922 that gdb has just sent, continue. */
923 if (thread->signaled)
925 thread->signaled = 0;
926 darwin_send_reply (inf, thread);
927 thread->msg_state = DARWIN_RUNNING;
928 status->kind = TARGET_WAITKIND_IGNORE;
931 else
932 status->value.sig = TARGET_EXC_SOFTWARE;
933 break;
934 case EXC_BREAKPOINT:
935 /* Many internal GDB routines expect breakpoints to be reported
936 as GDB_SIGNAL_TRAP, and will report TARGET_EXC_BREAKPOINT
937 as a spurious signal. */
938 status->value.sig = GDB_SIGNAL_TRAP;
939 break;
940 default:
941 status->value.sig = GDB_SIGNAL_UNKNOWN;
942 break;
945 return ptid_build (inf->pid, 0, thread->gdb_port);
948 *pinf = NULL;
949 *pthread = NULL;
951 inf = darwin_find_inferior_by_notify (hdr->msgh_local_port);
952 if (inf != NULL)
954 if (!inf->private->no_ptrace)
956 pid_t res;
957 int wstatus;
959 res = wait4 (inf->pid, &wstatus, 0, NULL);
960 if (res < 0 || res != inf->pid)
962 printf_unfiltered (_("wait4: res=%d: %s\n"),
963 res, safe_strerror (errno));
964 status->kind = TARGET_WAITKIND_SPURIOUS;
965 return minus_one_ptid;
967 if (WIFEXITED (wstatus))
969 status->kind = TARGET_WAITKIND_EXITED;
970 status->value.integer = WEXITSTATUS (wstatus);
972 else
974 status->kind = TARGET_WAITKIND_SIGNALLED;
975 status->value.sig = WTERMSIG (wstatus);
978 inferior_debug (4, _("darwin_wait: pid=%d exit, status=%x\n"),
979 res, wstatus);
981 /* Looks necessary on Leopard and harmless... */
982 wait4 (inf->pid, &wstatus, 0, NULL);
984 return ptid_build (inf->pid, 0, 0);
986 else
988 inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
989 status->kind = TARGET_WAITKIND_EXITED;
990 status->value.integer = 0; /* Don't know. */
991 return ptid_build (inf->pid, 0, 0);
995 printf_unfiltered (_("Bad local-port: %x\n"), hdr->msgh_local_port);
996 status->kind = TARGET_WAITKIND_SPURIOUS;
997 return minus_one_ptid;
1000 static int
1001 cancel_breakpoint (ptid_t ptid)
1003 /* Arrange for a breakpoint to be hit again later. We will handle
1004 the current event, eventually we will resume this thread, and this
1005 breakpoint will trap again.
1007 If we do not do this, then we run the risk that the user will
1008 delete or disable the breakpoint, but the thread will have already
1009 tripped on it. */
1011 struct regcache *regcache = get_thread_regcache (ptid);
1012 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1013 CORE_ADDR pc;
1015 pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
1016 if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
1018 inferior_debug (4, "cancel_breakpoint for thread %x\n",
1019 ptid_get_tid (ptid));
1021 /* Back up the PC if necessary. */
1022 if (gdbarch_decr_pc_after_break (gdbarch))
1023 regcache_write_pc (regcache, pc);
1025 return 1;
1027 return 0;
1030 static ptid_t
1031 darwin_wait (ptid_t ptid, struct target_waitstatus *status)
1033 kern_return_t kret;
1034 union
1036 mach_msg_header_t hdr;
1037 char data[0x100];
1038 } msgin;
1039 mach_msg_header_t *hdr = &msgin.hdr;
1040 ptid_t res;
1041 darwin_thread_t *thread;
1042 struct inferior *inf;
1044 inferior_debug
1045 (2, _("darwin_wait: waiting for a message pid=%d thread=%lx\n"),
1046 ptid_get_pid (ptid), ptid_get_tid (ptid));
1048 /* Handle fake stop events at first. */
1049 if (darwin_inf_fake_stop != NULL)
1051 inf = darwin_inf_fake_stop;
1052 darwin_inf_fake_stop = NULL;
1054 status->kind = TARGET_WAITKIND_STOPPED;
1055 status->value.sig = GDB_SIGNAL_TRAP;
1056 thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
1057 thread->msg_state = DARWIN_STOPPED;
1058 return ptid_build (inf->pid, 0, thread->gdb_port);
1063 /* set_sigint_trap (); */
1065 /* Wait for a message. */
1066 kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1067 sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1069 /* clear_sigint_trap (); */
1071 if (kret == MACH_RCV_INTERRUPTED)
1073 status->kind = TARGET_WAITKIND_IGNORE;
1074 return minus_one_ptid;
1077 if (kret != MACH_MSG_SUCCESS)
1079 inferior_debug (5, _("mach_msg: ret=%x\n"), kret);
1080 status->kind = TARGET_WAITKIND_SPURIOUS;
1081 return minus_one_ptid;
1084 /* Debug: display message. */
1085 if (darwin_debug_flag > 10)
1086 darwin_dump_message (hdr, darwin_debug_flag > 11);
1088 res = darwin_decode_message (hdr, &thread, &inf, status);
1090 if (inf == NULL)
1091 return res;
1093 while (status->kind == TARGET_WAITKIND_IGNORE);
1095 /* Stop all tasks. */
1096 iterate_over_inferiors (darwin_suspend_inferior_it, NULL);
1098 /* Read pending messages. */
1099 while (1)
1101 struct target_waitstatus status2;
1102 ptid_t ptid2;
1104 kret = mach_msg (&msgin.hdr,
1105 MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1106 sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1108 if (kret == MACH_RCV_TIMED_OUT)
1109 break;
1110 if (kret != MACH_MSG_SUCCESS)
1112 inferior_debug
1113 (5, _("darwin_wait: mach_msg(pending) ret=%x\n"), kret);
1114 break;
1117 ptid2 = darwin_decode_message (hdr, &thread, &inf, &status2);
1119 if (inf != NULL && thread != NULL
1120 && thread->event.ex_type == EXC_BREAKPOINT)
1122 if (thread->single_step
1123 || cancel_breakpoint (ptid_build (inf->pid, 0, thread->gdb_port)))
1125 gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1126 darwin_send_reply (inf, thread);
1127 thread->msg_state = DARWIN_RUNNING;
1129 else
1130 inferior_debug
1131 (3, _("darwin_wait: thread %x hit a non-gdb breakpoint\n"),
1132 thread->gdb_port);
1134 else
1135 inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1137 return res;
1140 static ptid_t
1141 darwin_wait_to (struct target_ops *ops,
1142 ptid_t ptid, struct target_waitstatus *status, int options)
1144 return darwin_wait (ptid, status);
1147 static void
1148 darwin_stop (ptid_t t)
1150 struct inferior *inf = current_inferior ();
1152 /* FIXME: handle in no_ptrace mode. */
1153 gdb_assert (!inf->private->no_ptrace);
1154 kill (inf->pid, SIGINT);
1157 static void
1158 darwin_mourn_inferior (struct target_ops *ops)
1160 struct inferior *inf = current_inferior ();
1161 kern_return_t kret;
1162 mach_port_t prev;
1163 int i;
1165 unpush_target (darwin_ops);
1167 /* Deallocate threads. */
1168 if (inf->private->threads)
1170 int k;
1171 darwin_thread_t *t;
1172 for (k = 0;
1173 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1174 k++)
1176 kret = mach_port_deallocate (gdb_task, t->gdb_port);
1177 MACH_CHECK_ERROR (kret);
1179 VEC_free (darwin_thread_t, inf->private->threads);
1180 inf->private->threads = NULL;
1183 kret = mach_port_move_member (gdb_task,
1184 inf->private->notify_port, MACH_PORT_NULL);
1185 gdb_assert (kret == KERN_SUCCESS);
1187 kret = mach_port_request_notification (gdb_task, inf->private->task,
1188 MACH_NOTIFY_DEAD_NAME, 0,
1189 MACH_PORT_NULL,
1190 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1191 &prev);
1192 /* This can fail if the task is dead. */
1193 inferior_debug (4, "task=%x, prev=%x, notify_port=%x\n",
1194 inf->private->task, prev, inf->private->notify_port);
1196 if (kret == KERN_SUCCESS)
1198 kret = mach_port_deallocate (gdb_task, prev);
1199 MACH_CHECK_ERROR (kret);
1202 kret = mach_port_destroy (gdb_task, inf->private->notify_port);
1203 MACH_CHECK_ERROR (kret);
1206 /* Deallocate saved exception ports. */
1207 for (i = 0; i < inf->private->exception_info.count; i++)
1209 kret = mach_port_deallocate
1210 (gdb_task, inf->private->exception_info.ports[i]);
1211 MACH_CHECK_ERROR (kret);
1213 inf->private->exception_info.count = 0;
1215 kret = mach_port_deallocate (gdb_task, inf->private->task);
1216 MACH_CHECK_ERROR (kret);
1218 xfree (inf->private);
1219 inf->private = NULL;
1221 generic_mourn_inferior ();
1224 static void
1225 darwin_reply_to_all_pending_messages (struct inferior *inf)
1227 int k;
1228 darwin_thread_t *t;
1230 for (k = 0;
1231 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1232 k++)
1234 if (t->msg_state == DARWIN_MESSAGE)
1235 darwin_resume_thread (inf, t, 0, 0);
1239 static void
1240 darwin_stop_inferior (struct inferior *inf)
1242 struct target_waitstatus wstatus;
1243 ptid_t ptid;
1244 kern_return_t kret;
1245 int status;
1246 int res;
1248 gdb_assert (inf != NULL);
1250 darwin_suspend_inferior (inf);
1252 darwin_reply_to_all_pending_messages (inf);
1254 if (inf->private->no_ptrace)
1255 return;
1257 res = kill (inf->pid, SIGSTOP);
1258 if (res != 0)
1259 warning (_("cannot kill: %s"), safe_strerror (errno));
1261 /* Wait until the process is really stopped. */
1262 while (1)
1264 ptid = darwin_wait (inferior_ptid, &wstatus);
1265 if (wstatus.kind == TARGET_WAITKIND_STOPPED
1266 && wstatus.value.sig == GDB_SIGNAL_STOP)
1267 break;
1271 static kern_return_t
1272 darwin_save_exception_ports (darwin_inferior *inf)
1274 kern_return_t kret;
1276 inf->exception_info.count =
1277 sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1279 kret = task_get_exception_ports
1280 (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1281 &inf->exception_info.count, inf->exception_info.ports,
1282 inf->exception_info.behaviors, inf->exception_info.flavors);
1283 return kret;
1286 static kern_return_t
1287 darwin_restore_exception_ports (darwin_inferior *inf)
1289 int i;
1290 kern_return_t kret;
1292 for (i = 0; i < inf->exception_info.count; i++)
1294 kret = task_set_exception_ports
1295 (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1296 inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1297 if (kret != KERN_SUCCESS)
1298 return kret;
1301 return KERN_SUCCESS;
1304 static void
1305 darwin_kill_inferior (struct target_ops *ops)
1307 struct inferior *inf = current_inferior ();
1308 struct target_waitstatus wstatus;
1309 ptid_t ptid;
1310 kern_return_t kret;
1311 int status;
1312 int res;
1314 if (ptid_equal (inferior_ptid, null_ptid))
1315 return;
1317 gdb_assert (inf != NULL);
1319 kret = darwin_restore_exception_ports (inf->private);
1320 MACH_CHECK_ERROR (kret);
1322 darwin_reply_to_all_pending_messages (inf);
1324 res = kill (inf->pid, 9);
1326 if (res == 0)
1328 darwin_resume_inferior (inf);
1330 ptid = darwin_wait (inferior_ptid, &wstatus);
1332 else if (errno != ESRCH)
1333 warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
1334 inf->pid, safe_strerror (errno));
1336 target_mourn_inferior ();
1339 static void
1340 darwin_attach_pid (struct inferior *inf)
1342 kern_return_t kret;
1343 mach_port_t prev_port;
1344 int traps_expected;
1345 mach_port_t prev_not;
1346 exception_mask_t mask;
1348 inf->private = XZALLOC (darwin_inferior);
1350 kret = task_for_pid (gdb_task, inf->pid, &inf->private->task);
1351 if (kret != KERN_SUCCESS)
1353 int status;
1355 if (!inf->attach_flag)
1357 kill (inf->pid, 9);
1358 waitpid (inf->pid, &status, 0);
1361 error (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
1362 " (please check gdb is codesigned - see taskgated(8))"),
1363 inf->pid, mach_error_string (kret), (unsigned long) kret);
1366 inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1367 inf->private->task, inf->pid);
1369 if (darwin_ex_port == MACH_PORT_NULL)
1371 /* Create a port to get exceptions. */
1372 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1373 &darwin_ex_port);
1374 gdb_assert (kret == KERN_SUCCESS);
1376 kret = mach_port_insert_right (gdb_task, darwin_ex_port, darwin_ex_port,
1377 MACH_MSG_TYPE_MAKE_SEND);
1378 gdb_assert (kret == KERN_SUCCESS);
1380 /* Create a port set and put ex_port in it. */
1381 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1382 &darwin_port_set);
1383 gdb_assert (kret == KERN_SUCCESS);
1385 kret = mach_port_move_member (gdb_task, darwin_ex_port, darwin_port_set);
1386 gdb_assert (kret == KERN_SUCCESS);
1389 /* Create a port to be notified when the child task terminates. */
1390 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1391 &inf->private->notify_port);
1392 gdb_assert (kret == KERN_SUCCESS);
1394 kret = mach_port_move_member (gdb_task,
1395 inf->private->notify_port, darwin_port_set);
1396 gdb_assert (kret == KERN_SUCCESS);
1398 kret = mach_port_request_notification (gdb_task, inf->private->task,
1399 MACH_NOTIFY_DEAD_NAME, 0,
1400 inf->private->notify_port,
1401 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1402 &prev_not);
1403 gdb_assert (kret == KERN_SUCCESS);
1404 gdb_assert (prev_not == MACH_PORT_NULL);
1406 kret = darwin_save_exception_ports (inf->private);
1407 gdb_assert (kret == KERN_SUCCESS);
1409 /* Set exception port. */
1410 if (enable_mach_exceptions)
1411 mask = EXC_MASK_ALL;
1412 else
1413 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1414 kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
1415 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1416 gdb_assert (kret == KERN_SUCCESS);
1418 push_target (darwin_ops);
1421 static void
1422 darwin_init_thread_list (struct inferior *inf)
1424 darwin_thread_t *thread;
1425 ptid_t new_ptid;
1427 darwin_check_new_threads (inf);
1429 gdb_assert (inf->private->threads
1430 && VEC_length (darwin_thread_t, inf->private->threads) > 0);
1431 thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
1433 /* Note: fork_inferior automatically add a thead but it uses a wrong ptid.
1434 Fix up. */
1435 new_ptid = ptid_build (inf->pid, 0, thread->gdb_port);
1436 thread_change_ptid (inferior_ptid, new_ptid);
1437 inferior_ptid = new_ptid;
1440 /* The child must synchronize with gdb: gdb must set the exception port
1441 before the child call PTRACE_SIGEXC. We use a pipe to achieve this.
1442 FIXME: is there a lighter way ? */
1443 static int ptrace_fds[2];
1445 static void
1446 darwin_ptrace_me (void)
1448 int res;
1449 char c;
1451 /* Close write end point. */
1452 close (ptrace_fds[1]);
1454 /* Wait until gdb is ready. */
1455 res = read (ptrace_fds[0], &c, 1);
1456 gdb_assert (res == 0);
1457 close (ptrace_fds[0]);
1459 /* Get rid of privileges. */
1460 setegid (getgid ());
1462 /* Set TRACEME. */
1463 PTRACE (PT_TRACE_ME, 0, 0, 0);
1465 /* Redirect signals to exception port. */
1466 PTRACE (PT_SIGEXC, 0, 0, 0);
1469 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2). */
1470 static void
1471 darwin_pre_ptrace (void)
1473 if (pipe (ptrace_fds) != 0)
1475 ptrace_fds[0] = -1;
1476 ptrace_fds[1] = -1;
1477 error (_("unable to create a pipe: %s"), safe_strerror (errno));
1481 static void
1482 darwin_ptrace_him (int pid)
1484 task_t itask;
1485 kern_return_t kret;
1486 mach_port_t prev_port;
1487 int traps_expected;
1488 struct inferior *inf = current_inferior ();
1490 darwin_attach_pid (inf);
1492 /* Let's the child run. */
1493 close (ptrace_fds[0]);
1494 close (ptrace_fds[1]);
1496 darwin_init_thread_list (inf);
1498 startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
1501 static void
1502 darwin_execvp (const char *file, char * const argv[], char * const env[])
1504 posix_spawnattr_t attr;
1505 short ps_flags = 0;
1506 int res;
1508 res = posix_spawnattr_init (&attr);
1509 if (res != 0)
1511 fprintf_unfiltered
1512 (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
1513 return;
1516 /* Do like execve: replace the image. */
1517 ps_flags = POSIX_SPAWN_SETEXEC;
1519 /* Disable ASLR. The constant doesn't look to be available outside the
1520 kernel include files. */
1521 #ifndef _POSIX_SPAWN_DISABLE_ASLR
1522 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
1523 #endif
1524 ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
1525 res = posix_spawnattr_setflags (&attr, ps_flags);
1526 if (res != 0)
1528 fprintf_unfiltered (gdb_stderr, "Cannot set posix_spawn flags\n");
1529 return;
1532 posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
1535 static void
1536 darwin_create_inferior (struct target_ops *ops, char *exec_file,
1537 char *allargs, char **env, int from_tty)
1539 /* Do the hard work. */
1540 fork_inferior (exec_file, allargs, env, darwin_ptrace_me, darwin_ptrace_him,
1541 darwin_pre_ptrace, NULL, darwin_execvp);
1543 /* Return now in case of error. */
1544 if (ptid_equal (inferior_ptid, null_ptid))
1545 return;
1549 /* Attach to process PID, then initialize for debugging it
1550 and wait for the trace-trap that results from attaching. */
1551 static void
1552 darwin_attach (struct target_ops *ops, char *args, int from_tty)
1554 pid_t pid;
1555 pid_t pid2;
1556 int wstatus;
1557 int res;
1558 struct inferior *inf;
1559 kern_return_t kret;
1561 pid = parse_pid_to_attach (args);
1563 if (pid == getpid ()) /* Trying to masturbate? */
1564 error (_("I refuse to debug myself!"));
1566 if (from_tty)
1568 char *exec_file = get_exec_file (0);
1570 if (exec_file)
1571 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
1572 target_pid_to_str (pid_to_ptid (pid)));
1573 else
1574 printf_unfiltered (_("Attaching to %s\n"),
1575 target_pid_to_str (pid_to_ptid (pid)));
1577 gdb_flush (gdb_stdout);
1580 if (pid == 0 || kill (pid, 0) < 0)
1581 error (_("Can't attach to process %d: %s (%d)"),
1582 pid, safe_strerror (errno), errno);
1584 inferior_ptid = pid_to_ptid (pid);
1585 inf = current_inferior ();
1586 inferior_appeared (inf, pid);
1587 inf->attach_flag = 1;
1589 /* Always add a main thread. */
1590 add_thread_silent (inferior_ptid);
1592 darwin_attach_pid (inf);
1594 darwin_suspend_inferior (inf);
1596 darwin_init_thread_list (inf);
1598 darwin_check_osabi (inf->private, ptid_get_tid (inferior_ptid));
1600 gdb_assert (darwin_inf_fake_stop == NULL);
1601 darwin_inf_fake_stop = inf;
1602 inf->private->no_ptrace = 1;
1605 /* Take a program previously attached to and detaches it.
1606 The program resumes execution and will no longer stop
1607 on signals, etc. We'd better not have left any breakpoints
1608 in the program or it'll die when it hits one. For this
1609 to work, it may be necessary for the process to have been
1610 previously attached. It *might* work if the program was
1611 started via fork. */
1612 static void
1613 darwin_detach (struct target_ops *ops, char *args, int from_tty)
1615 pid_t pid = ptid_get_pid (inferior_ptid);
1616 struct inferior *inf = current_inferior ();
1617 kern_return_t kret;
1618 int res;
1620 /* Display message. */
1621 if (from_tty)
1623 char *exec_file = get_exec_file (0);
1624 if (exec_file == 0)
1625 exec_file = "";
1626 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
1627 target_pid_to_str (pid_to_ptid (pid)));
1628 gdb_flush (gdb_stdout);
1631 /* If ptrace() is in use, stop the process. */
1632 if (!inf->private->no_ptrace)
1633 darwin_stop_inferior (inf);
1635 kret = darwin_restore_exception_ports (inf->private);
1636 MACH_CHECK_ERROR (kret);
1638 if (!inf->private->no_ptrace)
1640 res = PTRACE (PT_DETACH, inf->pid, 0, 0);
1641 if (res != 0)
1642 printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
1643 inf->pid, safe_strerror (errno), errno);
1646 darwin_reply_to_all_pending_messages (inf);
1648 /* When using ptrace, we have just performed a PT_DETACH, which
1649 resumes the inferior. On the other hand, when we are not using
1650 ptrace, we need to resume its execution ourselves. */
1651 if (inf->private->no_ptrace)
1652 darwin_resume_inferior (inf);
1654 darwin_mourn_inferior (ops);
1657 static void
1658 darwin_files_info (struct target_ops *ops)
1662 static char *
1663 darwin_pid_to_str (struct target_ops *ops, ptid_t ptid)
1665 static char buf[80];
1666 long tid = ptid_get_tid (ptid);
1668 if (tid != 0)
1670 snprintf (buf, sizeof (buf), _("Thread 0x%lx of process %u"),
1671 tid, ptid_get_pid (ptid));
1672 return buf;
1675 return normal_pid_to_str (ptid);
1678 static int
1679 darwin_thread_alive (struct target_ops *ops, ptid_t ptid)
1681 return 1;
1684 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
1685 copy it to RDADDR in gdb's address space.
1686 If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
1687 to ADDR in inferior task's address space.
1688 Return 0 on failure; number of bytes read / writen otherwise. */
1689 static int
1690 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
1691 char *rdaddr, const char *wraddr, int length)
1693 kern_return_t kret;
1694 mach_vm_address_t offset = addr & (mach_page_size - 1);
1695 mach_vm_address_t low_address = (mach_vm_address_t) (addr - offset);
1696 mach_vm_size_t aligned_length = (mach_vm_size_t) PAGE_ROUND (offset + length);
1697 pointer_t copied;
1698 int copy_count;
1699 mach_vm_size_t remaining_length;
1700 mach_vm_address_t region_address;
1701 mach_vm_size_t region_length;
1703 inferior_debug (8, _("darwin_read_write_inferior(task=%x, %s, len=%d)\n"),
1704 task, core_addr_to_string (addr), length);
1706 /* Get memory from inferior with page aligned addresses. */
1707 kret = mach_vm_read (task, low_address, aligned_length,
1708 &copied, &copy_count);
1709 if (kret != KERN_SUCCESS)
1711 inferior_debug
1712 (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
1713 core_addr_to_string (addr), mach_error_string (kret));
1714 return 0;
1717 if (rdaddr != NULL)
1718 memcpy (rdaddr, (char *)copied + offset, length);
1720 if (wraddr == NULL)
1721 goto out;
1723 memcpy ((char *)copied + offset, wraddr, length);
1725 /* Do writes atomically.
1726 First check for holes and unwritable memory. */
1727 for (region_address = low_address, remaining_length = aligned_length;
1728 region_address < low_address + aligned_length;
1729 region_address += region_length, remaining_length -= region_length)
1731 vm_region_submap_short_info_data_64_t info;
1732 mach_vm_address_t region_start = region_address;
1733 mach_msg_type_number_t count;
1734 natural_t region_depth;
1736 region_depth = 100000;
1737 count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
1738 kret = mach_vm_region_recurse
1739 (task, &region_start, &region_length, &region_depth,
1740 (vm_region_recurse_info_t) &info, &count);
1742 if (kret != KERN_SUCCESS)
1744 inferior_debug (1, _("darwin_read_write_inferior: "
1745 "mach_vm_region_recurse failed at %s: %s\n"),
1746 core_addr_to_string (region_address),
1747 mach_error_string (kret));
1748 goto out;
1751 inferior_debug
1752 (9, _("darwin_read_write_inferior: "
1753 "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
1754 core_addr_to_string (region_address),
1755 core_addr_to_string (region_start),
1756 core_addr_to_string (region_length));
1758 /* Check for holes in memory. */
1759 if (region_start > region_address)
1761 warning (_("No memory at %s (vs %s+0x%x). Nothing written"),
1762 core_addr_to_string (region_address),
1763 core_addr_to_string (region_start),
1764 (unsigned)region_length);
1765 length = 0;
1766 goto out;
1769 /* Adjust the length. */
1770 region_length -= (region_address - region_start);
1772 if (!(info.max_protection & VM_PROT_WRITE))
1774 kret = mach_vm_protect
1775 (task, region_address, region_length,
1776 TRUE, info.max_protection | VM_PROT_WRITE | VM_PROT_COPY);
1777 if (kret != KERN_SUCCESS)
1779 warning (_("darwin_read_write_inf: "
1780 "mach_vm_protect max failed at %s: %s"),
1781 core_addr_to_string (region_address),
1782 mach_error_string (kret));
1783 length = 0;
1784 goto out;
1788 if (!(info.protection & VM_PROT_WRITE))
1790 kret = mach_vm_protect (task, region_address, region_length,
1791 FALSE, info.protection | VM_PROT_WRITE);
1792 if (kret != KERN_SUCCESS)
1794 warning (_("darwin_read_write_inf: "
1795 "mach_vm_protect failed at %s (len=0x%lx): %s"),
1796 core_addr_to_string (region_address),
1797 (unsigned long)region_length, mach_error_string (kret));
1798 length = 0;
1799 goto out;
1804 kret = mach_vm_write (task, low_address, copied, aligned_length);
1806 if (kret != KERN_SUCCESS)
1808 warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
1809 mach_error_string (kret));
1810 length = 0;
1812 out:
1813 mach_vm_deallocate (mach_task_self (), copied, copy_count);
1814 return length;
1817 /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
1818 to RDADDR.
1819 Return 0 on failure; number of bytes read / written otherwise. */
1821 #ifdef TASK_DYLD_INFO_COUNT
1822 /* This is not available in Darwin 9. */
1823 static int
1824 darwin_read_dyld_info (task_t task, CORE_ADDR addr, char *rdaddr, int length)
1826 struct task_dyld_info task_dyld_info;
1827 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
1828 int sz = TASK_DYLD_INFO_COUNT * sizeof (natural_t);
1829 kern_return_t kret;
1831 if (addr >= sz)
1832 return 0;
1834 kret = task_info (task, TASK_DYLD_INFO, (task_info_t) &task_dyld_info, &count);
1835 MACH_CHECK_ERROR (kret);
1836 if (kret != KERN_SUCCESS)
1837 return -1;
1838 /* Truncate. */
1839 if (addr + length > sz)
1840 length = sz - addr;
1841 memcpy (rdaddr, (char *)&task_dyld_info + addr, length);
1842 return length;
1844 #endif
1847 /* Return 0 on failure, number of bytes handled otherwise. TARGET
1848 is ignored. */
1849 static int
1850 darwin_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len, int write,
1851 struct mem_attrib *attrib, struct target_ops *target)
1853 struct inferior *inf = current_inferior ();
1854 task_t task = inf->private->task;
1856 if (task == MACH_PORT_NULL)
1857 return 0;
1859 inferior_debug (8, _("darwin_xfer_memory(%s, %d, %c)\n"),
1860 core_addr_to_string (memaddr), len, write ? 'w' : 'r');
1862 if (write)
1863 return darwin_read_write_inferior (task, memaddr, NULL, myaddr, len);
1864 else
1865 return darwin_read_write_inferior (task, memaddr, myaddr, NULL, len);
1868 static LONGEST
1869 darwin_xfer_partial (struct target_ops *ops,
1870 enum target_object object, const char *annex,
1871 gdb_byte *readbuf, const gdb_byte *writebuf,
1872 ULONGEST offset, LONGEST len)
1874 struct inferior *inf = current_inferior ();
1876 inferior_debug
1877 (8, _("darwin_xfer_partial(%s, %d, rbuf=%s, wbuf=%s) pid=%u\n"),
1878 core_addr_to_string (offset), (int)len,
1879 host_address_to_string (readbuf), host_address_to_string (writebuf),
1880 inf->pid);
1882 switch (object)
1884 case TARGET_OBJECT_MEMORY:
1885 return darwin_read_write_inferior (inf->private->task, offset,
1886 readbuf, writebuf, len);
1887 #ifdef TASK_DYLD_INFO_COUNT
1888 case TARGET_OBJECT_DARWIN_DYLD_INFO:
1889 if (writebuf != NULL || readbuf == NULL)
1891 /* Support only read. */
1892 return -1;
1894 return darwin_read_dyld_info (inf->private->task, offset, readbuf, len);
1895 #endif
1896 default:
1897 return -1;
1902 static void
1903 set_enable_mach_exceptions (char *args, int from_tty,
1904 struct cmd_list_element *c)
1906 if (!ptid_equal (inferior_ptid, null_ptid))
1908 struct inferior *inf = current_inferior ();
1909 exception_mask_t mask;
1910 kern_return_t kret;
1912 if (enable_mach_exceptions)
1913 mask = EXC_MASK_ALL;
1914 else
1916 darwin_restore_exception_ports (inf->private);
1917 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1919 kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
1920 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1921 MACH_CHECK_ERROR (kret);
1925 static char *
1926 darwin_pid_to_exec_file (int pid)
1928 char *path;
1929 int res;
1931 path = xmalloc (MAXPATHLEN);
1932 make_cleanup (xfree, path);
1934 res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, MAXPATHLEN);
1935 if (res >= 0)
1936 return path;
1937 else
1938 return NULL;
1941 static ptid_t
1942 darwin_get_ada_task_ptid (long lwp, long thread)
1944 int i;
1945 darwin_thread_t *t;
1946 int k;
1947 struct inferior *inf = current_inferior ();
1948 kern_return_t kret;
1949 mach_port_name_array_t names;
1950 mach_msg_type_number_t names_count;
1951 mach_port_type_array_t types;
1952 mach_msg_type_number_t types_count;
1953 long res = 0;
1955 /* First linear search. */
1956 for (k = 0;
1957 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1958 k++)
1959 if (t->inf_port == lwp)
1960 return ptid_build (ptid_get_pid (inferior_ptid), 0, t->gdb_port);
1962 /* Maybe the port was never extract. Do it now. */
1964 /* First get inferior port names. */
1965 kret = mach_port_names (inf->private->task, &names, &names_count, &types,
1966 &types_count);
1967 MACH_CHECK_ERROR (kret);
1968 if (kret != KERN_SUCCESS)
1969 return null_ptid;
1971 /* For each name, copy the right in the gdb space and then compare with
1972 our view of the inferior threads. We don't forget to deallocate the
1973 right. */
1974 for (i = 0; i < names_count; i++)
1976 mach_port_t local_name;
1977 mach_msg_type_name_t local_type;
1979 /* We just need to know the corresponding name in gdb name space.
1980 So extract and deallocate the right. */
1981 kret = mach_port_extract_right (inf->private->task, names[i],
1982 MACH_MSG_TYPE_COPY_SEND,
1983 &local_name, &local_type);
1984 if (kret != KERN_SUCCESS)
1985 continue;
1986 mach_port_deallocate (gdb_task, local_name);
1988 for (k = 0;
1989 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1990 k++)
1991 if (t->gdb_port == local_name)
1993 t->inf_port = names[i];
1994 if (names[i] == lwp)
1995 res = t->gdb_port;
1999 vm_deallocate (gdb_task, (vm_address_t) names,
2000 names_count * sizeof (mach_port_t));
2002 if (res)
2003 return ptid_build (ptid_get_pid (inferior_ptid), 0, res);
2004 else
2005 return null_ptid;
2008 static int
2009 darwin_supports_multi_process (void)
2011 return 1;
2014 /* -Wmissing-prototypes */
2015 extern initialize_file_ftype _initialize_darwin_inferior;
2017 void
2018 _initialize_darwin_inferior (void)
2020 kern_return_t kret;
2022 gdb_task = mach_task_self ();
2023 darwin_host_self = mach_host_self ();
2025 /* Read page size. */
2026 kret = host_page_size (darwin_host_self, &mach_page_size);
2027 if (kret != KERN_SUCCESS)
2029 mach_page_size = 0x1000;
2030 MACH_CHECK_ERROR (kret);
2033 darwin_ops = inf_child_target ();
2035 darwin_ops->to_shortname = "darwin-child";
2036 darwin_ops->to_longname = _("Darwin child process");
2037 darwin_ops->to_doc =
2038 _("Darwin child process (started by the \"run\" command).");
2039 darwin_ops->to_create_inferior = darwin_create_inferior;
2040 darwin_ops->to_attach = darwin_attach;
2041 darwin_ops->to_attach_no_wait = 0;
2042 darwin_ops->to_detach = darwin_detach;
2043 darwin_ops->to_files_info = darwin_files_info;
2044 darwin_ops->to_wait = darwin_wait_to;
2045 darwin_ops->to_mourn_inferior = darwin_mourn_inferior;
2046 darwin_ops->to_kill = darwin_kill_inferior;
2047 darwin_ops->to_stop = darwin_stop;
2048 darwin_ops->to_resume = darwin_resume_to;
2049 darwin_ops->to_thread_alive = darwin_thread_alive;
2050 darwin_ops->to_pid_to_str = darwin_pid_to_str;
2051 darwin_ops->to_pid_to_exec_file = darwin_pid_to_exec_file;
2052 darwin_ops->to_load = NULL;
2053 darwin_ops->deprecated_xfer_memory = darwin_xfer_memory;
2054 darwin_ops->to_xfer_partial = darwin_xfer_partial;
2055 darwin_ops->to_supports_multi_process = darwin_supports_multi_process;
2056 darwin_ops->to_get_ada_task_ptid = darwin_get_ada_task_ptid;
2058 darwin_complete_target (darwin_ops);
2060 add_target (darwin_ops);
2062 inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"), mach_task_self (),
2063 getpid ());
2065 add_setshow_zuinteger_cmd ("darwin", class_obscure,
2066 &darwin_debug_flag, _("\
2067 Set if printing inferior communication debugging statements."), _("\
2068 Show if printing inferior communication debugging statements."), NULL,
2069 NULL, NULL,
2070 &setdebuglist, &showdebuglist);
2072 add_setshow_boolean_cmd ("mach-exceptions", class_support,
2073 &enable_mach_exceptions, _("\
2074 Set if mach exceptions are caught."), _("\
2075 Show if mach exceptions are caught."), _("\
2076 When this mode is on, all low level exceptions are reported before being\n\
2077 reported by the kernel."),
2078 &set_enable_mach_exceptions, NULL,
2079 &setlist, &showlist);