OSDN Git Service

add i18n markup in error message (utils.c:parse_escape)
[pf3gnuchains/sourceware.git] / gdb / darwin-nat.c
1 /* Darwin support for GDB, the GNU debugger.
2    Copyright (C) 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
3
4    Contributed by AdaCore.
5
6    This file is part of GDB.
7
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.
12
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.
17
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/>.
20 */
21
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
43 #include <sys/ptrace.h>
44 #include <sys/signal.h>
45 #include <machine/setjmp.h>
46 #include <sys/types.h>
47 #include <unistd.h>
48 #include <signal.h>
49 #include <string.h>
50 #include <ctype.h>
51 #include <sys/param.h>
52 #include <sys/sysctl.h>
53 #include <sys/proc.h>
54 #include <libproc.h>
55 #include <sys/syscall.h>
56
57 #include <mach/mach_error.h>
58 #include <mach/mach_vm.h>
59 #include <mach/mach_init.h>
60 #include <mach/vm_map.h>
61 #include <mach/task.h>
62 #include <mach/mach_port.h>
63 #include <mach/thread_act.h>
64 #include <mach/port.h>
65
66 #include "darwin-nat.h"
67
68 /* Quick overview.
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).
71
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
78    on Mach ports.
79
80    Some Mach documentation is available for Apple xnu source package or
81    from the web.  */
82
83
84 #define PTRACE(CMD, PID, ADDR, SIG) \
85  darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
86
87 extern boolean_t exc_server (mach_msg_header_t *in, mach_msg_header_t *out);
88
89 static void darwin_stop (ptid_t);
90
91 static void darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
92                               enum target_signal signal);
93 static void darwin_resume (ptid_t ptid, int step,
94                            enum target_signal signal);
95
96 static ptid_t darwin_wait_to (struct target_ops *ops, ptid_t ptid,
97                               struct target_waitstatus *status, int options);
98 static ptid_t darwin_wait (ptid_t ptid, struct target_waitstatus *status);
99
100 static void darwin_mourn_inferior (struct target_ops *ops);
101
102 static void darwin_kill_inferior (struct target_ops *ops);
103
104 static void darwin_ptrace_me (void);
105
106 static void darwin_ptrace_him (int pid);
107
108 static void darwin_create_inferior (struct target_ops *ops, char *exec_file,
109                                     char *allargs, char **env, int from_tty);
110
111 static void darwin_files_info (struct target_ops *ops);
112
113 static char *darwin_pid_to_str (struct target_ops *ops, ptid_t tpid);
114
115 static int darwin_thread_alive (struct target_ops *ops, ptid_t tpid);
116
117 /* Target operations for Darwin.  */
118 static struct target_ops *darwin_ops;
119
120 /* Task identifier of gdb.  */
121 static task_t gdb_task;
122
123 /* A copy of mach_host_self ().  */
124 mach_port_t darwin_host_self;
125
126 /* Exception port.  */
127 mach_port_t darwin_ex_port;
128
129 /* Port set.  */
130 mach_port_t darwin_port_set;
131
132 /* Page size.  */
133 static vm_size_t mach_page_size;
134
135 /* If Set, catch all mach exceptions (before they are converted to signals
136    by the kernel).  */
137 static int enable_mach_exceptions;
138
139 /* Inferior that should report a fake stop event.  */
140 static struct inferior *darwin_inf_fake_stop;
141
142 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
143 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
144
145 /* This controls output of inferior debugging.  */
146 static int darwin_debug_flag = 0;
147
148 /* Create a __TEXT __info_plist section in the executable so that gdb could
149    be signed.  This is required to get an authorization for task_for_pid.
150
151    Once gdb is built, you can either:
152    * make it setgid procmod
153    * or codesign it with any system-trusted signing authority.
154    See taskgated(8) for details.  */
155 static const unsigned char info_plist[]
156 __attribute__ ((section ("__TEXT,__info_plist"),used)) =
157   "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
158   "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
159   " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
160   "<plist version=\"1.0\">\n"
161   "<dict>\n"
162   "  <key>CFBundleIdentifier</key>\n"
163   "  <string>org.gnu.gdb</string>\n"
164   "  <key>CFBundleName</key>\n"
165   "  <string>gdb</string>\n"
166   "  <key>CFBundleVersion</key>\n"
167   "  <string>1.0</string>\n"
168   "  <key>SecTaskAccess</key>\n"
169   "  <array>\n"
170   "    <string>allowed</string>\n"
171   "    <string>debug</string>\n"
172   "  </array>\n"
173   "</dict>\n"
174   "</plist>\n";
175
176 static void
177 inferior_debug (int level, const char *fmt, ...)
178 {
179   va_list ap;
180
181   if (darwin_debug_flag < level)
182     return;
183
184   va_start (ap, fmt);
185   printf_unfiltered (_("[%d inferior]: "), getpid ());
186   vprintf_unfiltered (fmt, ap);
187   va_end (ap);
188 }
189
190 void
191 mach_check_error (kern_return_t ret, const char *file,
192                   unsigned int line, const char *func)
193 {
194   if (ret == KERN_SUCCESS)
195     return;
196   if (func == NULL)
197     func = _("[UNKNOWN]");
198
199   warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)\n"),
200            file, line, func, mach_error_string (ret), (unsigned long) ret);
201 }
202
203 static const char *
204 unparse_exception_type (unsigned int i)
205 {
206   static char unknown_exception_buf[32];
207
208   switch (i)
209     {
210     case EXC_BAD_ACCESS:
211       return "EXC_BAD_ACCESS";
212     case EXC_BAD_INSTRUCTION:
213       return "EXC_BAD_INSTRUCTION";
214     case EXC_ARITHMETIC:
215       return "EXC_ARITHMETIC";
216     case EXC_EMULATION:
217       return "EXC_EMULATION";
218     case EXC_SOFTWARE:
219       return "EXC_SOFTWARE";
220     case EXC_BREAKPOINT:
221       return "EXC_BREAKPOINT";
222     case EXC_SYSCALL:
223       return "EXC_SYSCALL";
224     case EXC_MACH_SYSCALL:
225       return "EXC_MACH_SYSCALL";
226     case EXC_RPC_ALERT:
227       return "EXC_RPC_ALERT";
228     case EXC_CRASH:
229       return "EXC_CRASH";
230     default:
231       snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
232       return unknown_exception_buf;
233     }
234 }
235
236 static int
237 darwin_ptrace (const char *name,
238                int request, int pid, PTRACE_TYPE_ARG3 arg3, int arg4)
239 {
240   int ret;
241
242   ret = ptrace (request, pid, (caddr_t) arg3, arg4);
243
244   inferior_debug (4, _("ptrace (%s, %d, 0x%x, %d): %d (%s)\n"),
245                   name, pid, arg3, arg4, ret,
246                   (ret != 0) ? safe_strerror (errno) : _("no error"));
247   return ret;
248 }
249
250 static int
251 cmp_thread_t (const void *l, const void *r)
252 {
253   thread_t tl = *(const thread_t *)l;
254   thread_t tr = *(const thread_t *)r;
255   return (int)(tl - tr);
256 }
257
258 static void
259 darwin_check_new_threads (struct inferior *inf)
260 {
261   kern_return_t kret;
262   unsigned int i;
263   thread_array_t thread_list;
264   unsigned int new_nbr;
265   unsigned int old_nbr;
266   unsigned int new_ix, old_ix;
267   darwin_inferior *darwin_inf = inf->private;
268   VEC (darwin_thread_t) *thread_vec;
269
270   /* Get list of threads.  */
271   kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
272   MACH_CHECK_ERROR (kret);
273   if (kret != KERN_SUCCESS)
274     return;
275
276   /* Sort the list.  */
277   if (new_nbr > 1)
278     qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
279
280   if (darwin_inf->threads)
281     old_nbr = VEC_length (darwin_thread_t, darwin_inf->threads);
282   else
283     old_nbr = 0;
284
285   /* Quick check for no changes.  */
286   if (old_nbr == new_nbr)
287     {
288       for (i = 0; i < new_nbr; i++)
289         if (thread_list[i]
290             != VEC_index (darwin_thread_t, darwin_inf->threads, i)->gdb_port)
291           break;
292       if (i == new_nbr)
293         {
294           kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
295                                 new_nbr * sizeof (int));
296           MACH_CHECK_ERROR (kret);
297           return;
298         }
299     }
300
301   thread_vec = VEC_alloc (darwin_thread_t, new_nbr);
302
303   for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
304     {
305       thread_t new_id = (new_ix < new_nbr) ?
306         thread_list[new_ix] : THREAD_NULL;
307       darwin_thread_t *old = (old_ix < old_nbr) ?
308         VEC_index (darwin_thread_t, darwin_inf->threads, old_ix) : NULL;
309       thread_t old_id = old ? old->gdb_port : THREAD_NULL;
310
311       inferior_debug
312         (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:%x old_id:%x\n"),
313          new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
314
315       if (old_id == new_id)
316         {
317           /* Thread still exist.  */
318           VEC_safe_push (darwin_thread_t, thread_vec, old);
319           new_ix++;
320           old_ix++;
321
322           kret = mach_port_deallocate (gdb_task, old_id);
323           MACH_CHECK_ERROR (kret);
324           continue;
325         }
326       if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
327         {
328           /* Ignore dead ports.
329              In some weird cases, we might get dead ports.  They should
330              correspond to dead thread so they could safely be ignored.  */
331           new_ix++;
332           continue;
333         }
334       if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
335         {
336           /* A thread was created.  */
337           struct thread_info *tp;
338           struct private_thread_info *pti;
339
340           pti = XZALLOC (struct private_thread_info);
341           pti->gdb_port = new_id;
342           pti->msg_state = DARWIN_RUNNING;
343
344           /* Add a new thread unless this is the first one ever met.  */
345           if (!(old_nbr == 0 && new_ix == 0))
346             tp = add_thread_with_info (ptid_build (inf->pid, 0, new_id), pti);
347           else
348             {
349               tp = find_thread_ptid (ptid_build (inf->pid, 0, 0));
350               gdb_assert (tp);
351               tp->private = pti;
352             }
353           VEC_safe_push (darwin_thread_t, thread_vec, pti);
354           new_ix++;
355           continue;
356         }
357       if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
358         {
359           /* A thread was removed.  */
360           delete_thread (ptid_build (inf->pid, 0, old_id));
361           kret = mach_port_deallocate (gdb_task, old_id);
362           MACH_CHECK_ERROR (kret);
363           old_ix++;
364           continue;
365         }
366       gdb_assert_not_reached ("unexpected thread case");
367     }
368
369   if (darwin_inf->threads)
370     VEC_free (darwin_thread_t, darwin_inf->threads);
371   darwin_inf->threads = thread_vec;
372
373   kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
374                         new_nbr * sizeof (int));
375   MACH_CHECK_ERROR (kret);
376 }
377
378 static int
379 find_inferior_task_it (struct inferior *inf, void *port_ptr)
380 {
381   return inf->private->task == *(task_t*)port_ptr;
382 }
383
384 static int
385 find_inferior_notify_it (struct inferior *inf, void *port_ptr)
386 {
387   return inf->private->notify_port == *(task_t*)port_ptr;
388 }
389
390 /* Return an inferior by task port.  */
391 static struct inferior *
392 darwin_find_inferior_by_task (task_t port)
393 {
394   return iterate_over_inferiors (&find_inferior_task_it, &port);
395 }
396
397 /* Return an inferior by notification port.  */
398 static struct inferior *
399 darwin_find_inferior_by_notify (mach_port_t port)
400 {
401   return iterate_over_inferiors (&find_inferior_notify_it, &port);
402 }
403
404 /* Return a thread by port.  */
405 static darwin_thread_t *
406 darwin_find_thread (struct inferior *inf, thread_t thread)
407 {
408   darwin_thread_t *t;
409   int k;
410
411   for (k = 0;
412        VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
413        k++)
414     if (t->gdb_port == thread)
415       return t;
416   return NULL;
417 }
418
419 /* Suspend (ie stop) an inferior at Mach level.  */
420
421 static void
422 darwin_suspend_inferior (struct inferior *inf)
423 {
424   if (!inf->private->suspended)
425     {
426       kern_return_t kret;
427
428       kret = task_suspend (inf->private->task);
429       MACH_CHECK_ERROR (kret);
430
431       inf->private->suspended = 1;
432     }
433 }
434
435 /* Resume an inferior at Mach level.  */
436
437 static void
438 darwin_resume_inferior (struct inferior *inf)
439 {
440   if (inf->private->suspended)
441     {
442       kern_return_t kret;
443
444       kret = task_resume (inf->private->task);
445       MACH_CHECK_ERROR (kret);
446
447       inf->private->suspended = 0;
448     }
449 }
450
451 /* Iterator functions.  */
452
453 static int
454 darwin_suspend_inferior_it (struct inferior *inf, void *arg)
455 {
456   darwin_suspend_inferior (inf);
457   darwin_check_new_threads (inf);
458   return 0;
459 }
460
461 static int
462 darwin_resume_inferior_it (struct inferior *inf, void *arg)
463 {
464   darwin_resume_inferior (inf);
465   return 0;
466 }
467
468 static void
469 darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
470 {
471   printf_unfiltered (_("message header:\n"));
472   printf_unfiltered (_(" bits: 0x%x\n"), hdr->msgh_bits);
473   printf_unfiltered (_(" size: 0x%x\n"), hdr->msgh_size);
474   printf_unfiltered (_(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
475   printf_unfiltered (_(" local-port: 0x%x\n"), hdr->msgh_local_port);
476   printf_unfiltered (_(" reserved: 0x%x\n"), hdr->msgh_reserved);
477   printf_unfiltered (_(" id: 0x%x\n"), hdr->msgh_id);
478
479   if (disp_body)
480     {
481       const unsigned char *data;
482       const unsigned long *ldata;
483       int size;
484       int i;
485
486       data = (unsigned char *)(hdr + 1);
487       size = hdr->msgh_size - sizeof (mach_msg_header_t);
488
489       if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
490         {
491           mach_msg_body_t *bod = (mach_msg_body_t*)data;
492           mach_msg_port_descriptor_t *desc =
493             (mach_msg_port_descriptor_t *)(bod + 1);
494           int k;
495           NDR_record_t *ndr;
496           printf_unfiltered (_("body: descriptor_count=%u\n"),
497                              bod->msgh_descriptor_count);
498           data += sizeof (mach_msg_body_t);
499           size -= sizeof (mach_msg_body_t);
500           for (k = 0; k < bod->msgh_descriptor_count; k++)
501             switch (desc[k].type)
502               {
503               case MACH_MSG_PORT_DESCRIPTOR:
504                 printf_unfiltered
505                   (_(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
506                    k, desc[k].type, desc[k].name, desc[k].disposition);
507                 break;
508               default:
509                 printf_unfiltered (_(" descr %d: type=%u\n"),
510                                    k, desc[k].type);
511                 break;
512               }
513           data += bod->msgh_descriptor_count
514             * sizeof (mach_msg_port_descriptor_t);
515           size -= bod->msgh_descriptor_count
516             * sizeof (mach_msg_port_descriptor_t);
517           ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
518           printf_unfiltered
519             (_("NDR: mig=%02x if=%02x encod=%02x "
520                "int=%02x char=%02x float=%02x\n"),
521              ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
522              ndr->int_rep, ndr->char_rep, ndr->float_rep);
523           data += sizeof (NDR_record_t);
524           size -= sizeof (NDR_record_t);
525         }
526
527       printf_unfiltered (_("  data:"));
528       ldata = (const unsigned long *)data;
529       for (i = 0; i < size / sizeof (unsigned long); i++)
530         printf_unfiltered (" %08lx", ldata[i]);
531       printf_unfiltered (_("\n"));
532     }
533 }
534
535 static int
536 darwin_decode_exception_message (mach_msg_header_t *hdr,
537                                  struct inferior **pinf,
538                                  darwin_thread_t **pthread)
539 {
540   mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
541   mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
542   NDR_record_t *ndr;
543   integer_t *data;
544   struct inferior *inf;
545   darwin_thread_t *thread;
546   task_t task_port;
547   thread_t thread_port;
548   kern_return_t kret;
549   int i;
550
551   /* Check message identifier.  2401 is exc.  */
552   if (hdr->msgh_id != 2401)
553     return -1;
554
555   /* Check message header.  */
556   if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
557     return -1;
558
559   /* Check descriptors.  */
560   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
561                         + sizeof (*ndr) + 2 * sizeof (integer_t))
562       || bod->msgh_descriptor_count != 2
563       || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
564       || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
565       || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
566       || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
567     return -1;
568
569   /* Check data representation.  */
570   ndr = (NDR_record_t *)(desc + 2);
571   if (ndr->mig_vers != NDR_PROTOCOL_2_0
572       || ndr->if_vers != NDR_PROTOCOL_2_0
573       || ndr->mig_encoding != NDR_record.mig_encoding
574       || ndr->int_rep != NDR_record.int_rep
575       || ndr->char_rep != NDR_record.char_rep
576       || ndr->float_rep != NDR_record.float_rep)
577     return -1;
578
579   /* Ok, the hard work.  */
580   data = (integer_t *)(ndr + 1);
581
582   /* Find process by port.  */
583   task_port = desc[1].name;
584   thread_port = desc[0].name;
585   inf = darwin_find_inferior_by_task (task_port);
586   if (inf == NULL)
587     return -1;
588   *pinf = inf;
589
590   /* Find thread by port.  */
591   /* Check for new threads.  Do it early so that the port in the exception
592      message can be deallocated.  */
593   darwin_check_new_threads (inf);
594
595   /* We got new rights to the task and the thread.  Get rid of them.  */
596   kret = mach_port_deallocate (mach_task_self (), task_port);
597   MACH_CHECK_ERROR (kret);
598   kret = mach_port_deallocate (mach_task_self (), thread_port);
599   MACH_CHECK_ERROR (kret);
600
601   thread = darwin_find_thread (inf, thread_port);
602   if (thread == NULL)
603     return -1;
604   *pthread = thread;
605
606   /* Finish decoding.  */
607   gdb_assert (thread->msg_state == DARWIN_RUNNING);
608   thread->event.header = *hdr;
609   thread->event.thread_port = thread_port;
610   thread->event.task_port = task_port;
611   thread->event.ex_type = data[0];
612   thread->event.data_count = data[1];
613
614   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
615                         + sizeof (*ndr) + 2 * sizeof (integer_t)
616                         + data[1] * sizeof (integer_t)))
617       return -1;
618   for (i = 0; i < data[1]; i++)
619     thread->event.ex_data[i] = data[2 + i];
620
621   thread->msg_state = DARWIN_MESSAGE;
622
623   return 0;
624 }
625
626 static void
627 darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
628                      integer_t code)
629 {
630   mach_msg_header_t *rh = &reply->Head;
631   rh->msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(hdr->msgh_bits), 0);
632   rh->msgh_remote_port = hdr->msgh_remote_port;
633   rh->msgh_size = (mach_msg_size_t)sizeof(mig_reply_error_t);
634   rh->msgh_local_port = MACH_PORT_NULL;
635   rh->msgh_id = hdr->msgh_id + 100;
636
637   reply->NDR = NDR_record;
638   reply->RetCode = code;
639 }
640
641 static void
642 darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
643 {
644   kern_return_t kret;
645   mig_reply_error_t reply;
646
647   darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
648
649   kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
650                    reply.Head.msgh_size, 0,
651                    MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
652                    MACH_PORT_NULL);
653   MACH_CHECK_ERROR (kret);
654
655   inf->private->pending_messages--;
656 }
657
658 static void
659 darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
660                       int step, int nsignal)
661 {
662   kern_return_t kret;
663   int res;
664
665   inferior_debug
666     (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
667      thread->msg_state, thread->gdb_port, step, nsignal);
668
669   switch (thread->msg_state)
670     {
671     case DARWIN_MESSAGE:
672       if (thread->event.ex_type == EXC_SOFTWARE
673           && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
674         {
675           /* Either deliver a new signal or cancel the signal received.  */
676           res = PTRACE (PT_THUPDATE, inf->pid,
677                         (void *)(uintptr_t)thread->gdb_port, nsignal);
678           if (res < 0)
679             inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
680         }
681       else if (nsignal)
682         {
683           /* Note: ptrace is allowed only if the process is stopped.
684              Directly send the signal to the thread.  */
685           res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
686           inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
687                           thread->gdb_port, nsignal, res);
688           thread->signaled = 1;
689         }
690
691       /* Set single step.  */
692       inferior_debug (4, _("darwin_set_sstep (thread=%x, enable=%d)\n"),
693                       thread->gdb_port, step);
694       darwin_set_sstep (thread->gdb_port, step);
695       thread->single_step = step;
696
697       darwin_send_reply (inf, thread);
698       thread->msg_state = DARWIN_RUNNING;
699       break;
700
701     case DARWIN_RUNNING:
702       break;
703
704     case DARWIN_STOPPED:
705       kret = thread_resume (thread->gdb_port);
706       MACH_CHECK_ERROR (kret);
707
708       thread->msg_state = DARWIN_RUNNING;
709       break;
710     }
711 }
712
713 /* Resume all threads of the inferior.  */
714
715 static void
716 darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
717 {
718   darwin_thread_t *thread;
719   int k;
720
721   for (k = 0;
722        VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
723        k++)
724     darwin_resume_thread (inf, thread, step, nsignal);
725 }
726
727 struct resume_inferior_threads_param
728 {
729   int step;
730   int nsignal;
731 };
732
733 static int
734 darwin_resume_inferior_threads_it (struct inferior *inf, void *param)
735 {
736   int step = ((struct resume_inferior_threads_param *)param)->step;
737   int nsignal = ((struct resume_inferior_threads_param *)param)->nsignal;
738
739   darwin_resume_inferior_threads (inf, step, nsignal);
740
741   return 0;
742 }
743
744 /* Suspend all threads of INF.  */
745
746 static void
747 darwin_suspend_inferior_threads (struct inferior *inf)
748 {
749   darwin_thread_t *thread;
750   kern_return_t kret;
751   int k;
752
753   for (k = 0;
754        VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
755        k++)
756     switch (thread->msg_state)
757       {
758       case DARWIN_STOPPED:
759       case DARWIN_MESSAGE:
760         break;
761       case DARWIN_RUNNING:
762         kret = thread_suspend (thread->gdb_port);
763         MACH_CHECK_ERROR (kret);
764         thread->msg_state = DARWIN_STOPPED;
765         break;
766       }
767 }
768
769 static void
770 darwin_resume (ptid_t ptid, int step, enum target_signal signal)
771 {
772   struct target_waitstatus status;
773   int pid;
774
775   kern_return_t kret;
776   int res;
777   int nsignal;
778   struct inferior *inf;
779
780   inferior_debug
781     (2, _("darwin_resume: pid=%d, tid=0x%x, step=%d, signal=%d\n"),
782      ptid_get_pid (ptid), ptid_get_tid (ptid), step, signal);
783
784   if (signal == TARGET_SIGNAL_0)
785     nsignal = 0;
786   else
787     nsignal = target_signal_to_host (signal);
788
789   /* Don't try to single step all threads.  */
790   if (step)
791     ptid = inferior_ptid;
792
793   /* minus_one_ptid is RESUME_ALL.  */
794   if (ptid_equal (ptid, minus_one_ptid))
795     {
796       struct resume_inferior_threads_param param;
797
798       param.nsignal = nsignal;
799       param.step = step;
800
801       /* Resume threads.  */
802       iterate_over_inferiors (darwin_resume_inferior_threads_it, &param);
803       /* Resume tasks.  */
804       iterate_over_inferiors (darwin_resume_inferior_it, NULL);
805     }
806   else
807     {
808       struct inferior *inf = find_inferior_pid (ptid_get_pid (ptid));
809       long tid = ptid_get_tid (ptid);
810
811       /* Stop the inferior (should be useless).  */
812       darwin_suspend_inferior (inf);
813
814       if (tid == 0)
815         darwin_resume_inferior_threads (inf, step, nsignal);
816       else
817         {
818           darwin_thread_t *thread;
819
820           /* Suspend threads of the task.  */
821           darwin_suspend_inferior_threads (inf);
822
823           /* Resume the selected thread.  */
824           thread = darwin_find_thread (inf, tid);
825           gdb_assert (thread);
826           darwin_resume_thread (inf, thread, step, nsignal);
827         }
828
829       /* Resume the task.  */
830       darwin_resume_inferior (inf);
831     }
832 }
833
834 static void
835 darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
836                   enum target_signal signal)
837 {
838   return darwin_resume (ptid, step, signal);
839 }
840
841 static ptid_t
842 darwin_decode_message (mach_msg_header_t *hdr,
843                        darwin_thread_t **pthread,
844                        struct inferior **pinf,
845                        struct target_waitstatus *status)
846 {
847   darwin_thread_t *thread;
848   struct inferior *inf;
849
850   /* Exception message.  */
851   if (hdr->msgh_local_port == darwin_ex_port)
852     {
853       int res;
854
855       /* Decode message.  */
856       res = darwin_decode_exception_message (hdr, &inf, &thread);
857
858       if (res < 0)
859         {
860           /* Should not happen...  */
861           printf_unfiltered (_("darwin_wait: ill-formatted message (id=%x)\n"),
862                              hdr->msgh_id);
863           /* FIXME: send a failure reply?  */
864           status->kind = TARGET_WAITKIND_SPURIOUS;
865           return minus_one_ptid;
866         }
867       *pinf = inf;
868       *pthread = thread;
869       inf->private->pending_messages++;
870
871       status->kind = TARGET_WAITKIND_STOPPED;
872       thread->msg_state = DARWIN_MESSAGE;
873
874       inferior_debug (4, _("darwin_wait: thread=%x, got %s\n"),
875                       thread->gdb_port,
876                       unparse_exception_type (thread->event.ex_type));
877
878       switch (thread->event.ex_type)
879         {
880         case EXC_BAD_ACCESS:
881           status->value.sig = TARGET_EXC_BAD_ACCESS;
882           break;
883         case EXC_BAD_INSTRUCTION:
884           status->value.sig = TARGET_EXC_BAD_INSTRUCTION;
885           break;
886         case EXC_ARITHMETIC:
887           status->value.sig = TARGET_EXC_ARITHMETIC;
888           break;
889         case EXC_EMULATION:
890           status->value.sig = TARGET_EXC_EMULATION;
891           break;
892         case EXC_SOFTWARE:
893           if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
894             {
895               status->value.sig =
896                 target_signal_from_host (thread->event.ex_data[1]);
897               inferior_debug (5, _("  (signal %d: %s)\n"),
898                               thread->event.ex_data[1],
899                               target_signal_to_name (status->value.sig));
900
901               /* If the thread is stopped because it has received a signal
902                  that gdb has just sent, continue.  */
903               if (thread->signaled)
904                 {
905                   thread->signaled = 0;
906                   darwin_send_reply (inf, thread);
907                   thread->msg_state = DARWIN_RUNNING;
908                   status->kind = TARGET_WAITKIND_IGNORE;
909                 }
910             }
911           else
912             status->value.sig = TARGET_EXC_SOFTWARE;
913           break;
914         case EXC_BREAKPOINT:
915           /* Many internal GDB routines expect breakpoints to be reported
916              as TARGET_SIGNAL_TRAP, and will report TARGET_EXC_BREAKPOINT
917              as a spurious signal.  */
918           status->value.sig = TARGET_SIGNAL_TRAP;
919           break;
920         default:
921           status->value.sig = TARGET_SIGNAL_UNKNOWN;
922           break;
923         }
924
925       return ptid_build (inf->pid, 0, thread->gdb_port);
926     }
927
928   *pinf = NULL;
929   *pthread = NULL;
930
931   inf = darwin_find_inferior_by_notify (hdr->msgh_local_port);
932   if (inf != NULL)
933     {
934       if (!inf->private->no_ptrace)
935         {
936           pid_t res;
937           int wstatus;
938
939           res = wait4 (inf->pid, &wstatus, 0, NULL);
940           if (res < 0 || res != inf->pid)
941             {
942               printf_unfiltered (_("wait4: res=%d: %s\n"),
943                                  res, safe_strerror (errno));
944               status->kind = TARGET_WAITKIND_SPURIOUS;
945               return minus_one_ptid;
946             }
947           if (WIFEXITED (wstatus))
948             {
949               status->kind = TARGET_WAITKIND_EXITED;
950               status->value.integer = WEXITSTATUS (wstatus);
951             }
952           else
953             {
954               status->kind = TARGET_WAITKIND_SIGNALLED;
955               status->value.sig = WTERMSIG (wstatus);
956             }
957
958           inferior_debug (4, _("darwin_wait: pid=%d exit, status=%x\n"),
959                           res, wstatus);
960
961           /* Looks necessary on Leopard and harmless...  */
962           wait4 (inf->pid, &wstatus, 0, NULL);
963
964           return ptid_build (inf->pid, 0, 0);
965         }
966       else
967         {
968           inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
969           status->kind = TARGET_WAITKIND_EXITED;
970           status->value.integer = 0; /* Don't know.  */
971           return ptid_build (inf->pid, 0, 0);
972         }
973     }
974
975   printf_unfiltered (_("Bad local-port: %x\n"), hdr->msgh_local_port);
976   status->kind = TARGET_WAITKIND_SPURIOUS;
977   return minus_one_ptid;
978 }
979
980 static int
981 cancel_breakpoint (ptid_t ptid)
982 {
983   /* Arrange for a breakpoint to be hit again later.  We will handle
984      the current event, eventually we will resume this thread, and this
985      breakpoint will trap again.
986
987      If we do not do this, then we run the risk that the user will
988      delete or disable the breakpoint, but the thread will have already
989      tripped on it.  */
990
991   struct regcache *regcache = get_thread_regcache (ptid);
992   struct gdbarch *gdbarch = get_regcache_arch (regcache);
993   CORE_ADDR pc;
994
995   pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
996   if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
997     {
998       inferior_debug (4, "cancel_breakpoint for thread %x\n",
999                       ptid_get_tid (ptid));
1000
1001       /* Back up the PC if necessary.  */
1002       if (gdbarch_decr_pc_after_break (gdbarch))
1003         regcache_write_pc (regcache, pc);
1004
1005       return 1;
1006     }
1007   return 0;
1008 }
1009
1010 static ptid_t
1011 darwin_wait (ptid_t ptid, struct target_waitstatus *status)
1012 {
1013   kern_return_t kret;
1014   union
1015   {
1016     mach_msg_header_t hdr;
1017     char data[0x100];
1018   } msgin;
1019   mach_msg_header_t *hdr = &msgin.hdr;
1020   ptid_t res;
1021   darwin_thread_t *thread;
1022   struct inferior *inf;
1023
1024   inferior_debug
1025     (2, _("darwin_wait: waiting for a message pid=%d thread=%lx\n"),
1026      ptid_get_pid (ptid), ptid_get_tid (ptid));
1027
1028   /* Handle fake stop events at first.  */
1029   if (darwin_inf_fake_stop != NULL)
1030     {
1031       inf = darwin_inf_fake_stop;
1032       darwin_inf_fake_stop = NULL;
1033
1034       status->kind = TARGET_WAITKIND_STOPPED;
1035       status->value.sig = TARGET_SIGNAL_TRAP;
1036       thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
1037       thread->msg_state = DARWIN_STOPPED;
1038       return ptid_build (inf->pid, 0, thread->gdb_port);
1039     }
1040
1041   do
1042     {
1043       /* set_sigint_trap (); */
1044
1045       /* Wait for a message.  */
1046       kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1047                        sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1048
1049       /* clear_sigint_trap (); */
1050
1051       if (kret == MACH_RCV_INTERRUPTED)
1052         {
1053           status->kind = TARGET_WAITKIND_IGNORE;
1054           return minus_one_ptid;
1055         }
1056
1057       if (kret != MACH_MSG_SUCCESS)
1058         {
1059           inferior_debug (5, _("mach_msg: ret=%x\n"), kret);
1060           status->kind = TARGET_WAITKIND_SPURIOUS;
1061           return minus_one_ptid;
1062         }
1063
1064       /* Debug: display message.  */
1065       if (darwin_debug_flag > 10)
1066         darwin_dump_message (hdr, darwin_debug_flag > 11);
1067
1068       res = darwin_decode_message (hdr, &thread, &inf, status);
1069
1070       if (inf == NULL)
1071         return res;
1072     }
1073   while (status->kind == TARGET_WAITKIND_IGNORE);
1074
1075   /* Stop all tasks.  */
1076   iterate_over_inferiors (darwin_suspend_inferior_it, NULL);
1077
1078   /* Read pending messages.  */
1079   while (1)
1080     {
1081       struct target_waitstatus status2;
1082       ptid_t ptid2;
1083
1084       kret = mach_msg (&msgin.hdr,
1085                        MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1086                        sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1087
1088       if (kret == MACH_RCV_TIMED_OUT)
1089         break;
1090       if (kret != MACH_MSG_SUCCESS)
1091         {
1092           inferior_debug
1093             (5, _("darwin_wait: mach_msg(pending) ret=%x\n"), kret);
1094           break;
1095         }
1096
1097       ptid2 = darwin_decode_message (hdr, &thread, &inf, &status2);
1098
1099       if (inf != NULL && thread != NULL
1100           && thread->event.ex_type == EXC_BREAKPOINT)
1101         {
1102           if (thread->single_step
1103               || cancel_breakpoint (ptid_build (inf->pid, 0, thread->gdb_port)))
1104             {
1105               gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1106               darwin_send_reply (inf, thread);
1107               thread->msg_state = DARWIN_RUNNING;
1108             }
1109           else
1110             inferior_debug
1111               (3, _("darwin_wait: thread %x hit a non-gdb breakpoint\n"),
1112                thread->gdb_port);
1113         }
1114       else
1115         inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1116     }
1117   return res;
1118 }
1119
1120 static ptid_t
1121 darwin_wait_to (struct target_ops *ops, 
1122                 ptid_t ptid, struct target_waitstatus *status, int options)
1123 {
1124   return darwin_wait (ptid, status);
1125 }
1126
1127 static void
1128 darwin_stop (ptid_t t)
1129 {
1130   struct inferior *inf = current_inferior ();
1131
1132   /* FIXME: handle in no_ptrace mode.  */
1133   gdb_assert (!inf->private->no_ptrace);
1134   kill (inf->pid, SIGINT);
1135 }
1136
1137 static void
1138 darwin_mourn_inferior (struct target_ops *ops)
1139 {
1140   struct inferior *inf = current_inferior ();
1141   kern_return_t kret;
1142   mach_port_t prev;
1143   int i;
1144
1145   unpush_target (darwin_ops);
1146
1147   /* Deallocate threads.  */
1148   if (inf->private->threads)
1149     {
1150       int k;
1151       darwin_thread_t *t;
1152       for (k = 0;
1153            VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1154            k++)
1155         {
1156           kret = mach_port_deallocate (gdb_task, t->gdb_port);
1157           MACH_CHECK_ERROR (kret);
1158         }
1159       VEC_free (darwin_thread_t, inf->private->threads);
1160       inf->private->threads = NULL;
1161     }
1162
1163   kret = mach_port_move_member (gdb_task,
1164                                 inf->private->notify_port, MACH_PORT_NULL);
1165   gdb_assert (kret == KERN_SUCCESS);
1166
1167   kret = mach_port_request_notification (gdb_task, inf->private->task,
1168                                          MACH_NOTIFY_DEAD_NAME, 0,
1169                                          MACH_PORT_NULL,
1170                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
1171                                          &prev);
1172   /* This can fail if the task is dead.  */
1173   inferior_debug (4, "task=%x, prev=%x, notify_port=%x\n",
1174                   inf->private->task, prev, inf->private->notify_port);
1175
1176   if (kret == KERN_SUCCESS)
1177     {
1178       kret = mach_port_deallocate (gdb_task, prev);
1179       MACH_CHECK_ERROR (kret);
1180     }
1181
1182   kret = mach_port_destroy (gdb_task, inf->private->notify_port);
1183   MACH_CHECK_ERROR (kret);
1184
1185
1186   /* Deallocate saved exception ports.  */
1187   for (i = 0; i < inf->private->exception_info.count; i++)
1188     {
1189       kret = mach_port_deallocate
1190         (gdb_task, inf->private->exception_info.ports[i]);
1191       MACH_CHECK_ERROR (kret);
1192     }
1193   inf->private->exception_info.count = 0;
1194
1195   kret = mach_port_deallocate (gdb_task, inf->private->task);
1196   MACH_CHECK_ERROR (kret);
1197
1198   xfree (inf->private);
1199   inf->private = NULL;
1200
1201   generic_mourn_inferior ();
1202 }
1203
1204 static void
1205 darwin_reply_to_all_pending_messages (struct inferior *inf)
1206 {
1207   int k;
1208   darwin_thread_t *t;
1209
1210   for (k = 0;
1211        VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1212        k++)
1213     {
1214       if (t->msg_state == DARWIN_MESSAGE)
1215         darwin_resume_thread (inf, t, 0, 0);
1216     }
1217 }
1218
1219 static void
1220 darwin_stop_inferior (struct inferior *inf)
1221 {
1222   struct target_waitstatus wstatus;
1223   ptid_t ptid;
1224   kern_return_t kret;
1225   int status;
1226   int res;
1227
1228   gdb_assert (inf != NULL);
1229
1230   darwin_suspend_inferior (inf);
1231
1232   darwin_reply_to_all_pending_messages (inf);
1233
1234   if (inf->private->no_ptrace)
1235     return;
1236
1237   res = kill (inf->pid, SIGSTOP);
1238   if (res != 0)
1239     warning (_("cannot kill: %s\n"), safe_strerror (errno));
1240
1241   /* Wait until the process is really stopped.  */
1242   while (1)
1243     {
1244       ptid = darwin_wait (inferior_ptid, &wstatus);
1245       if (wstatus.kind == TARGET_WAITKIND_STOPPED
1246           && wstatus.value.sig == TARGET_SIGNAL_STOP)
1247         break;
1248     }
1249 }
1250
1251 static kern_return_t
1252 darwin_save_exception_ports (darwin_inferior *inf)
1253 {
1254   kern_return_t kret;
1255
1256   inf->exception_info.count =
1257     sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1258
1259   kret = task_get_exception_ports
1260     (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1261      &inf->exception_info.count, inf->exception_info.ports,
1262      inf->exception_info.behaviors, inf->exception_info.flavors);
1263   return kret;
1264 }
1265
1266 static kern_return_t
1267 darwin_restore_exception_ports (darwin_inferior *inf)
1268 {
1269   int i;
1270   kern_return_t kret;
1271
1272   for (i = 0; i < inf->exception_info.count; i++)
1273     {
1274       kret = task_set_exception_ports
1275         (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1276          inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1277       if (kret != KERN_SUCCESS)
1278         return kret;
1279     }
1280
1281   return KERN_SUCCESS;
1282 }
1283
1284 static void
1285 darwin_kill_inferior (struct target_ops *ops)
1286 {
1287   struct inferior *inf = current_inferior ();
1288   struct target_waitstatus wstatus;
1289   ptid_t ptid;
1290   kern_return_t kret;
1291   int status;
1292   int res;
1293
1294   if (ptid_equal (inferior_ptid, null_ptid))
1295     return;
1296
1297   gdb_assert (inf != NULL);
1298
1299   if (!inf->private->no_ptrace)
1300     {
1301       darwin_stop_inferior (inf);
1302
1303       res = PTRACE (PT_KILL, inf->pid, 0, 0);
1304       gdb_assert (res == 0);
1305
1306       darwin_reply_to_all_pending_messages (inf);
1307
1308       darwin_resume_inferior (inf);
1309
1310       ptid = darwin_wait (inferior_ptid, &wstatus);
1311     }
1312   else
1313     {
1314       kret = darwin_restore_exception_ports (inf->private);
1315       MACH_CHECK_ERROR (kret);
1316
1317       darwin_reply_to_all_pending_messages (inf);
1318
1319       darwin_resume_inferior (inf);
1320
1321       res = kill (inf->pid, 9);
1322
1323       ptid = darwin_wait (inferior_ptid, &wstatus);
1324     }
1325
1326   target_mourn_inferior ();
1327 }
1328
1329 static void
1330 darwin_attach_pid (struct inferior *inf)
1331 {
1332   kern_return_t kret;
1333   mach_port_t prev_port;
1334   int traps_expected;
1335   mach_port_t prev_not;
1336   exception_mask_t mask;
1337
1338   inf->private = XZALLOC (darwin_inferior);
1339
1340   kret = task_for_pid (gdb_task, inf->pid, &inf->private->task);
1341   if (kret != KERN_SUCCESS)
1342     {
1343       int status;
1344
1345       if (!inf->attach_flag)
1346         {
1347           kill (inf->pid, 9);
1348           waitpid (inf->pid, &status, 0);
1349         }
1350
1351       error (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
1352                " (please check gdb is codesigned - see taskgated(8))"),
1353              inf->pid, mach_error_string (kret), (unsigned long) kret);
1354     }
1355
1356   inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1357                   inf->private->task, inf->pid);
1358
1359   if (darwin_ex_port == MACH_PORT_NULL)
1360     {
1361       /* Create a port to get exceptions.  */
1362       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1363                                  &darwin_ex_port);
1364       gdb_assert (kret == KERN_SUCCESS);
1365
1366       kret = mach_port_insert_right (gdb_task, darwin_ex_port, darwin_ex_port,
1367                                      MACH_MSG_TYPE_MAKE_SEND);
1368       gdb_assert (kret == KERN_SUCCESS);
1369
1370       /* Create a port set and put ex_port in it.  */
1371       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1372                                  &darwin_port_set);
1373       gdb_assert (kret == KERN_SUCCESS);
1374
1375       kret = mach_port_move_member (gdb_task, darwin_ex_port, darwin_port_set);
1376       gdb_assert (kret == KERN_SUCCESS);
1377     }
1378
1379   /* Create a port to be notified when the child task terminates.  */
1380   kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1381                              &inf->private->notify_port);
1382   gdb_assert (kret == KERN_SUCCESS);
1383
1384   kret = mach_port_move_member (gdb_task,
1385                                 inf->private->notify_port, darwin_port_set);
1386   gdb_assert (kret == KERN_SUCCESS);
1387
1388   kret = mach_port_request_notification (gdb_task, inf->private->task,
1389                                          MACH_NOTIFY_DEAD_NAME, 0,
1390                                          inf->private->notify_port,
1391                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
1392                                          &prev_not);
1393   gdb_assert (kret == KERN_SUCCESS);
1394   gdb_assert (prev_not == MACH_PORT_NULL);
1395
1396   kret = darwin_save_exception_ports (inf->private);
1397   gdb_assert (kret == KERN_SUCCESS);
1398
1399   /* Set exception port.  */
1400   if (enable_mach_exceptions)
1401     mask = EXC_MASK_ALL;
1402   else
1403     mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1404   kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
1405                                    EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1406   gdb_assert (kret == KERN_SUCCESS);
1407
1408   push_target (darwin_ops);
1409 }
1410
1411 static void
1412 darwin_init_thread_list (struct inferior *inf)
1413 {
1414   darwin_thread_t *thread;
1415   ptid_t new_ptid;
1416
1417   darwin_check_new_threads (inf);
1418
1419   gdb_assert (inf->private->threads
1420               && VEC_length (darwin_thread_t, inf->private->threads) > 0);
1421   thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
1422
1423   /* Note: fork_inferior automatically add a thead but it uses a wrong ptid.
1424      Fix up.  */
1425   new_ptid = ptid_build (inf->pid, 0, thread->gdb_port);
1426   thread_change_ptid (inferior_ptid, new_ptid);
1427   inferior_ptid = new_ptid;
1428 }
1429
1430 /* The child must synchronize with gdb: gdb must set the exception port
1431    before the child call PTRACE_SIGEXC.  We use a pipe to achieve this.
1432    FIXME: is there a lighter way ?  */
1433 static int ptrace_fds[2];
1434
1435 static void
1436 darwin_ptrace_me (void)
1437 {
1438   int res;
1439   char c;
1440
1441   /* Close write end point.  */
1442   close (ptrace_fds[1]);
1443
1444   /* Wait until gdb is ready.  */
1445   res = read (ptrace_fds[0], &c, 1);
1446   gdb_assert (res == 0);
1447   close (ptrace_fds[0]);
1448
1449   /* Get rid of privileges.  */
1450   setegid (getgid ());
1451
1452   /* Set TRACEME.  */
1453   PTRACE (PT_TRACE_ME, 0, 0, 0);
1454
1455   /* Redirect signals to exception port.  */
1456   PTRACE (PT_SIGEXC, 0, 0, 0);
1457 }
1458
1459 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).  */
1460 static void
1461 darwin_pre_ptrace (void)
1462 {
1463   if (pipe (ptrace_fds) != 0)
1464     {
1465       ptrace_fds[0] = -1;
1466       ptrace_fds[1] = -1;
1467       error (_("unable to create a pipe: %s"), safe_strerror (errno));
1468     }
1469 }
1470
1471 static void
1472 darwin_ptrace_him (int pid)
1473 {
1474   task_t itask;
1475   kern_return_t kret;
1476   mach_port_t prev_port;
1477   int traps_expected;
1478   struct inferior *inf = current_inferior ();
1479
1480   darwin_attach_pid (inf);
1481
1482   /* Let's the child run.  */
1483   close (ptrace_fds[0]);
1484   close (ptrace_fds[1]);
1485
1486   darwin_init_thread_list (inf);
1487
1488   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
1489 }
1490
1491 static void
1492 darwin_create_inferior (struct target_ops *ops, char *exec_file,
1493                         char *allargs, char **env, int from_tty)
1494 {
1495   /* Do the hard work.  */
1496   fork_inferior (exec_file, allargs, env, darwin_ptrace_me, darwin_ptrace_him,
1497                  darwin_pre_ptrace, NULL);
1498
1499   /* Return now in case of error.  */
1500   if (ptid_equal (inferior_ptid, null_ptid))
1501     return;
1502 }
1503 \f
1504
1505 /* Attach to process PID, then initialize for debugging it
1506    and wait for the trace-trap that results from attaching.  */
1507 static void
1508 darwin_attach (struct target_ops *ops, char *args, int from_tty)
1509 {
1510   pid_t pid;
1511   pid_t pid2;
1512   int wstatus;
1513   int res;
1514   struct inferior *inf;
1515   kern_return_t kret;
1516
1517   pid = parse_pid_to_attach (args);
1518
1519   if (pid == getpid ())         /* Trying to masturbate?  */
1520     error (_("I refuse to debug myself!"));
1521
1522   if (from_tty)
1523     {
1524       char *exec_file = get_exec_file (0);
1525
1526       if (exec_file)
1527         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
1528                            target_pid_to_str (pid_to_ptid (pid)));
1529       else
1530         printf_unfiltered (_("Attaching to %s\n"),
1531                            target_pid_to_str (pid_to_ptid (pid)));
1532
1533       gdb_flush (gdb_stdout);
1534     }
1535
1536   if (pid == 0 || kill (pid, 0) < 0)
1537     error (_("Can't attach to process %d: %s (%d)"),
1538            pid, safe_strerror (errno), errno);
1539
1540   inferior_ptid = pid_to_ptid (pid);
1541   inf = current_inferior ();
1542   inferior_appeared (inf, pid);
1543   inf->attach_flag = 1;
1544
1545   /* Always add a main thread.  */
1546   add_thread_silent (inferior_ptid);
1547
1548   darwin_attach_pid (inf);
1549
1550   darwin_suspend_inferior (inf);
1551
1552   darwin_init_thread_list (inf);
1553
1554   darwin_check_osabi (inf->private, ptid_get_tid (inferior_ptid));
1555
1556   gdb_assert (darwin_inf_fake_stop == NULL);
1557   darwin_inf_fake_stop = inf;
1558   inf->private->no_ptrace = 1;
1559 }
1560
1561 /* Take a program previously attached to and detaches it.
1562    The program resumes execution and will no longer stop
1563    on signals, etc.  We'd better not have left any breakpoints
1564    in the program or it'll die when it hits one.  For this
1565    to work, it may be necessary for the process to have been
1566    previously attached.  It *might* work if the program was
1567    started via fork.  */
1568 static void
1569 darwin_detach (struct target_ops *ops, char *args, int from_tty)
1570 {
1571   pid_t pid = ptid_get_pid (inferior_ptid);
1572   struct inferior *inf = current_inferior ();
1573   kern_return_t kret;
1574   int res;
1575
1576   /* Display message.  */
1577   if (from_tty)
1578     {
1579       char *exec_file = get_exec_file (0);
1580       if (exec_file == 0)
1581         exec_file = "";
1582       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
1583                          target_pid_to_str (pid_to_ptid (pid)));
1584       gdb_flush (gdb_stdout);
1585     }
1586
1587   /* If ptrace() is in use, stop the process.  */
1588   if (!inf->private->no_ptrace)
1589     darwin_stop_inferior (inf);
1590
1591   kret = darwin_restore_exception_ports (inf->private);
1592   MACH_CHECK_ERROR (kret);
1593
1594   if (!inf->private->no_ptrace)
1595     {
1596       res = PTRACE (PT_DETACH, inf->pid, 0, 0);
1597       if (res != 0)
1598         printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
1599                            inf->pid, safe_strerror (errno), errno);
1600     }
1601
1602   darwin_reply_to_all_pending_messages (inf);
1603
1604   darwin_resume_inferior (inf);
1605
1606   darwin_mourn_inferior (ops);
1607 }
1608
1609 static void
1610 darwin_files_info (struct target_ops *ops)
1611 {
1612 }
1613
1614 static char *
1615 darwin_pid_to_str (struct target_ops *ops, ptid_t ptid)
1616 {
1617   static char buf[80];
1618   long tid = ptid_get_tid (ptid);
1619
1620   if (tid != 0)
1621     {
1622       snprintf (buf, sizeof (buf), _("Thread 0x%lx of process %u"),
1623                 tid, ptid_get_pid (ptid));
1624       return buf;
1625     }
1626
1627   return normal_pid_to_str (ptid);
1628 }
1629
1630 static int
1631 darwin_thread_alive (struct target_ops *ops, ptid_t ptid)
1632 {
1633   return 1;
1634 }
1635
1636 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
1637    copy it to RDADDR in gdb's address space.
1638    If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
1639    to ADDR in inferior task's address space.
1640    Return 0 on failure; number of bytes read / writen  otherwise.  */
1641 static int
1642 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
1643                             char *rdaddr, const char *wraddr, int length)
1644 {
1645   kern_return_t kret;
1646   mach_vm_address_t offset = addr & (mach_page_size - 1);
1647   mach_vm_address_t low_address = (mach_vm_address_t) (addr - offset);
1648   mach_vm_size_t aligned_length = (mach_vm_size_t) PAGE_ROUND (offset + length);
1649   pointer_t copied;
1650   int copy_count;
1651   mach_vm_size_t remaining_length;
1652   mach_vm_address_t region_address;
1653   mach_vm_size_t region_length;
1654
1655   inferior_debug (8, _("darwin_read_write_inferior(task=%x, %s, len=%d)\n"),
1656                   task, core_addr_to_string (addr), length);
1657
1658   /* Get memory from inferior with page aligned addresses.  */
1659   kret = mach_vm_read (task, low_address, aligned_length,
1660                       &copied, &copy_count);
1661   if (kret != KERN_SUCCESS)
1662     {
1663       inferior_debug
1664         (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
1665          core_addr_to_string (addr), mach_error_string (kret));
1666       return 0;
1667     }
1668
1669   if (rdaddr != NULL)
1670     memcpy (rdaddr, (char *)copied + offset, length);
1671
1672   if (wraddr == NULL)
1673     goto out;
1674
1675   memcpy ((char *)copied + offset, wraddr, length);
1676
1677   /* Do writes atomically.
1678      First check for holes and unwritable memory.  */
1679   for (region_address = low_address, remaining_length = aligned_length;
1680        region_address < low_address + aligned_length;
1681        region_address += region_length, remaining_length -= region_length)
1682     {
1683       vm_region_submap_short_info_data_64_t info;
1684       mach_vm_address_t region_start = region_address;
1685       mach_msg_type_number_t count;
1686       natural_t region_depth;
1687
1688       region_depth = 100000;
1689       count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
1690       kret = mach_vm_region_recurse
1691         (task, &region_start, &region_length, &region_depth,
1692          (vm_region_recurse_info_t) &info, &count);
1693
1694       if (kret != KERN_SUCCESS)
1695         {
1696           inferior_debug (1, _("darwin_read_write_inferior: "
1697                                "mach_vm_region_recurse failed at %s: %s\n"),
1698                           core_addr_to_string (region_address),
1699                           mach_error_string (kret));
1700           goto out;
1701         }
1702
1703       inferior_debug
1704         (9, _("darwin_read_write_inferior: "
1705               "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
1706          core_addr_to_string (region_address),
1707          core_addr_to_string (region_start),
1708          core_addr_to_string (region_length));
1709
1710       /* Check for holes in memory.  */
1711       if (region_start > region_address)
1712         {
1713           warning (_("No memory at %s (vs %s+0x%x).  Nothing written"),
1714                    core_addr_to_string (region_address),
1715                    core_addr_to_string (region_start),
1716                    (unsigned)region_length);
1717           length = 0;
1718           goto out;
1719         }
1720
1721       /* Adjust the length.  */
1722       region_length -= (region_address - region_start);
1723
1724       if (!(info.max_protection & VM_PROT_WRITE))
1725         {
1726           kret = mach_vm_protect
1727             (task, region_address, region_length,
1728              TRUE, info.max_protection | VM_PROT_WRITE | VM_PROT_COPY);
1729           if (kret != KERN_SUCCESS)
1730             {
1731               warning (_("darwin_read_write_inf: "
1732                          "mach_vm_protect max failed at %s: %s"),
1733                        core_addr_to_string (region_address),
1734                        mach_error_string (kret));
1735               length = 0;
1736               goto out;
1737             }
1738         }
1739
1740       if (!(info.protection & VM_PROT_WRITE))
1741         {
1742           kret = mach_vm_protect (task, region_address, region_length,
1743                                  FALSE, info.protection | VM_PROT_WRITE);
1744           if (kret != KERN_SUCCESS)
1745             {
1746               warning (_("darwin_read_write_inf: "
1747                          "mach_vm_protect failed at %s (len=0x%lx): %s"),
1748                        core_addr_to_string (region_address),
1749                        (unsigned long)region_length, mach_error_string (kret));
1750               length = 0;
1751               goto out;
1752             }
1753         }
1754     }
1755
1756   kret = mach_vm_write (task, low_address, copied, aligned_length);
1757
1758   if (kret != KERN_SUCCESS)
1759     {
1760       warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
1761                mach_error_string (kret));
1762       length = 0;
1763     }
1764 out:
1765   mach_vm_deallocate (mach_task_self (), copied, copy_count);
1766   return length;
1767 }
1768
1769 \f
1770 /* Return 0 on failure, number of bytes handled otherwise.  TARGET
1771    is ignored.  */
1772 static int
1773 darwin_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len, int write,
1774                     struct mem_attrib *attrib, struct target_ops *target)
1775 {
1776   struct inferior *inf = current_inferior ();
1777   task_t task = inf->private->task;
1778
1779   if (task == MACH_PORT_NULL)
1780     return 0;
1781
1782   inferior_debug (8, _("darwin_xfer_memory(%s, %d, %c)\n"),
1783                   core_addr_to_string (memaddr), len, write ? 'w' : 'r');
1784
1785   if (write)
1786     return darwin_read_write_inferior (task, memaddr, NULL, myaddr, len);
1787   else
1788     return darwin_read_write_inferior (task, memaddr, myaddr, NULL, len);
1789 }
1790
1791 static LONGEST
1792 darwin_xfer_partial (struct target_ops *ops,
1793                      enum target_object object, const char *annex,
1794                      gdb_byte *readbuf, const gdb_byte *writebuf,
1795                      ULONGEST offset, LONGEST len)
1796 {
1797   struct inferior *inf = current_inferior ();
1798
1799   inferior_debug
1800     (8, _("darwin_xfer_partial(%s, %d, rbuf=%s, wbuf=%s) pid=%u\n"),
1801      core_addr_to_string (offset), (int)len,
1802      host_address_to_string (readbuf), host_address_to_string (writebuf),
1803      inf->pid);
1804
1805   if (object != TARGET_OBJECT_MEMORY)
1806     return -1;
1807
1808   return darwin_read_write_inferior (inf->private->task, offset,
1809                                      readbuf, writebuf, len);
1810 }
1811
1812 static void
1813 set_enable_mach_exceptions (char *args, int from_tty,
1814                             struct cmd_list_element *c)
1815 {
1816   if (!ptid_equal (inferior_ptid, null_ptid))
1817     {
1818       struct inferior *inf = current_inferior ();
1819       exception_mask_t mask;
1820       kern_return_t kret;
1821
1822       if (enable_mach_exceptions)
1823         mask = EXC_MASK_ALL;
1824       else
1825         {
1826           darwin_restore_exception_ports (inf->private);
1827           mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1828         }
1829       kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
1830                                        EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1831       MACH_CHECK_ERROR (kret);
1832     }
1833 }
1834
1835 static char *
1836 darwin_pid_to_exec_file (int pid)
1837 {
1838   char *path;
1839   int res;
1840
1841   path = xmalloc (MAXPATHLEN);
1842   make_cleanup (xfree, path);
1843
1844   res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, MAXPATHLEN);
1845   if (res >= 0)
1846     return path;
1847   else
1848     return NULL;
1849 }
1850
1851 static ptid_t
1852 darwin_get_ada_task_ptid (long lwp, long thread)
1853 {
1854   int i;
1855   darwin_thread_t *t;
1856   int k;
1857   struct inferior *inf = current_inferior ();
1858   kern_return_t kret;
1859   mach_port_name_array_t names;
1860   mach_msg_type_number_t names_count;
1861   mach_port_type_array_t types;
1862   mach_msg_type_number_t types_count;
1863   long res = 0;
1864
1865   /* First linear search.  */
1866   for (k = 0;
1867        VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1868        k++)
1869     if (t->inf_port == lwp)
1870       return ptid_build (ptid_get_pid (inferior_ptid), 0, t->gdb_port);
1871
1872   /* Maybe the port was never extract.  Do it now.  */
1873
1874   /* First get inferior port names.  */
1875   kret = mach_port_names (inf->private->task, &names, &names_count, &types,
1876                           &types_count);
1877   MACH_CHECK_ERROR (kret);
1878   if (kret != KERN_SUCCESS)
1879     return null_ptid;
1880
1881   /* For each name, copy the right in the gdb space and then compare with
1882      our view of the inferior threads.  We don't forget to deallocate the
1883      right.  */
1884   for (i = 0; i < names_count; i++)
1885     {
1886       mach_port_t local_name;
1887       mach_msg_type_name_t local_type;
1888
1889       /* We just need to know the corresponding name in gdb name space.
1890          So extract and deallocate the right.  */
1891       kret = mach_port_extract_right (inf->private->task, names[i],
1892                                       MACH_MSG_TYPE_COPY_SEND,
1893                                       &local_name, &local_type);
1894       if (kret != KERN_SUCCESS)
1895         continue;
1896       mach_port_deallocate (gdb_task, local_name);
1897
1898       for (k = 0;
1899            VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1900            k++)
1901         if (t->gdb_port == local_name)
1902           {
1903             t->inf_port = names[i];
1904             if (names[i] == lwp)
1905               res = t->gdb_port;
1906           }
1907     }
1908
1909   vm_deallocate (gdb_task, (vm_address_t) names,
1910                  names_count * sizeof (mach_port_t));
1911
1912   if (res)
1913     return ptid_build (ptid_get_pid (inferior_ptid), 0, res);
1914   else
1915     return null_ptid;
1916 }
1917
1918 static int
1919 darwin_supports_multi_process (void)
1920 {
1921   return 1;
1922 }
1923
1924 void
1925 _initialize_darwin_inferior (void)
1926 {
1927   kern_return_t kret;
1928
1929   gdb_task = mach_task_self ();
1930   darwin_host_self = mach_host_self ();
1931
1932   /* Read page size.  */
1933   kret = host_page_size (darwin_host_self, &mach_page_size);
1934   if (kret != KERN_SUCCESS)
1935     {
1936       mach_page_size = 0x1000;
1937       MACH_CHECK_ERROR (kret);
1938     }
1939
1940   darwin_ops = inf_child_target ();
1941
1942   darwin_ops->to_shortname = "darwin-child";
1943   darwin_ops->to_longname = _("Darwin child process");
1944   darwin_ops->to_doc =
1945     _("Darwin child process (started by the \"run\" command).");
1946   darwin_ops->to_create_inferior = darwin_create_inferior;
1947   darwin_ops->to_attach = darwin_attach;
1948   darwin_ops->to_attach_no_wait = 0;
1949   darwin_ops->to_detach = darwin_detach;
1950   darwin_ops->to_files_info = darwin_files_info;
1951   darwin_ops->to_wait = darwin_wait_to;
1952   darwin_ops->to_mourn_inferior = darwin_mourn_inferior;
1953   darwin_ops->to_kill = darwin_kill_inferior;
1954   darwin_ops->to_stop = darwin_stop;
1955   darwin_ops->to_resume = darwin_resume_to;
1956   darwin_ops->to_thread_alive = darwin_thread_alive;
1957   darwin_ops->to_pid_to_str = darwin_pid_to_str;
1958   darwin_ops->to_pid_to_exec_file = darwin_pid_to_exec_file;
1959   darwin_ops->to_load = NULL;
1960   darwin_ops->deprecated_xfer_memory = darwin_xfer_memory;
1961   darwin_ops->to_xfer_partial = darwin_xfer_partial;
1962   darwin_ops->to_supports_multi_process = darwin_supports_multi_process;
1963   darwin_ops->to_get_ada_task_ptid = darwin_get_ada_task_ptid;
1964
1965   darwin_complete_target (darwin_ops);
1966
1967   add_target (darwin_ops);
1968
1969   inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"), mach_task_self (),
1970                   getpid ());
1971
1972   add_setshow_zinteger_cmd ("darwin", class_obscure,
1973                             &darwin_debug_flag, _("\
1974 Set if printing inferior communication debugging statements."), _("\
1975 Show if printing inferior communication debugging statements."), NULL,
1976                             NULL, NULL,
1977                             &setdebuglist, &showdebuglist);
1978
1979   add_setshow_boolean_cmd ("mach-exceptions", class_support,
1980                            &enable_mach_exceptions, _("\
1981 Set if mach exceptions are caught."), _("\
1982 Show if mach exceptions are caught."), _("\
1983 When this mode is on, all low level exceptions are reported before being\n\
1984 reported by the kernel."),
1985                            &set_enable_mach_exceptions, NULL,
1986                            &setlist, &showlist);
1987 }