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