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