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