s/get_regcache_arch (regcache)/regcache->arch ()/g
[external/binutils.git] / gdb / darwin-nat.c
1 /* Darwin support for GDB, the GNU debugger.
2    Copyright (C) 2008-2017 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 #include "defs.h"
22 #include "top.h"
23 #include "inferior.h"
24 #include "target.h"
25 #include "symfile.h"
26 #include "symtab.h"
27 #include "objfiles.h"
28 #include "gdb.h"
29 #include "gdbcmd.h"
30 #include "gdbcore.h"
31 #include "gdbthread.h"
32 #include "regcache.h"
33 #include "event-top.h"
34 #include "inf-loop.h"
35 #include <sys/stat.h>
36 #include "inf-child.h"
37 #include "value.h"
38 #include "arch-utils.h"
39 #include "bfd.h"
40 #include "bfd/mach-o.h"
41
42 #include <sys/ptrace.h>
43 #include <sys/signal.h>
44 #include <setjmp.h>
45 #include <sys/types.h>
46 #include <unistd.h>
47 #include <signal.h>
48 #include <ctype.h>
49 #include <sys/sysctl.h>
50 #include <sys/proc.h>
51 #include <libproc.h>
52 #include <sys/syscall.h>
53 #include <spawn.h>
54
55 #include <mach/mach_error.h>
56 #include <mach/mach_vm.h>
57 #include <mach/mach_init.h>
58 #include <mach/vm_map.h>
59 #include <mach/task.h>
60 #include <mach/mach_port.h>
61 #include <mach/thread_act.h>
62 #include <mach/port.h>
63
64 #include "darwin-nat.h"
65 #include "common/filestuff.h"
66 #include "nat/fork-inferior.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 static void darwin_interrupt (struct target_ops *self, ptid_t);
88
89 static void darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
90                               enum gdb_signal signal);
91 static void darwin_resume (ptid_t ptid, int step,
92                            enum gdb_signal signal);
93
94 static ptid_t darwin_wait_to (struct target_ops *ops, ptid_t ptid,
95                               struct target_waitstatus *status, int options);
96 static ptid_t darwin_wait (ptid_t ptid, struct target_waitstatus *status);
97
98 static void darwin_mourn_inferior (struct target_ops *ops);
99
100 static void darwin_kill_inferior (struct target_ops *ops);
101
102 static void darwin_ptrace_me (void);
103
104 static void darwin_ptrace_him (int pid);
105
106 static void darwin_create_inferior (struct target_ops *ops,
107                                     const char *exec_file,
108                                     const std::string &allargs,
109                                     char **env, int from_tty);
110
111 static void darwin_files_info (struct target_ops *ops);
112
113 static const 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 static void darwin_encode_reply (mig_reply_error_t *reply,
118                                  mach_msg_header_t *hdr, integer_t code);
119
120 static void darwin_setup_request_notification (struct inferior *inf);
121 static void darwin_deallocate_exception_ports (darwin_inferior *inf);
122 static void darwin_setup_exceptions (struct inferior *inf);
123 static void darwin_deallocate_threads (struct inferior *inf);
124
125 /* Target operations for Darwin.  */
126 static struct target_ops *darwin_ops;
127
128 /* Task identifier of gdb.  */
129 static task_t gdb_task;
130
131 /* A copy of mach_host_self ().  */
132 mach_port_t darwin_host_self;
133
134 /* Exception port.  */
135 mach_port_t darwin_ex_port;
136
137 /* Port set, to wait for answer on all ports.  */
138 mach_port_t darwin_port_set;
139
140 /* Page size.  */
141 static vm_size_t mach_page_size;
142
143 /* If Set, catch all mach exceptions (before they are converted to signals
144    by the kernel).  */
145 static int enable_mach_exceptions;
146
147 /* Inferior that should report a fake stop event.  */
148 static struct inferior *darwin_inf_fake_stop;
149
150 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
151 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
152
153 /* This controls output of inferior debugging.  */
154 static unsigned int darwin_debug_flag = 0;
155
156 /* Create a __TEXT __info_plist section in the executable so that gdb could
157    be signed.  This is required to get an authorization for task_for_pid.
158
159    Once gdb is built, you must codesign it with any system-trusted signing
160    authority.  See taskgated(8) for details.  */
161 static const unsigned char info_plist[]
162 __attribute__ ((section ("__TEXT,__info_plist"),used)) =
163   "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
164   "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
165   " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
166   "<plist version=\"1.0\">\n"
167   "<dict>\n"
168   "  <key>CFBundleIdentifier</key>\n"
169   "  <string>org.gnu.gdb</string>\n"
170   "  <key>CFBundleName</key>\n"
171   "  <string>gdb</string>\n"
172   "  <key>CFBundleVersion</key>\n"
173   "  <string>1.0</string>\n"
174   "  <key>SecTaskAccess</key>\n"
175   "  <array>\n"
176   "    <string>allowed</string>\n"
177   "    <string>debug</string>\n"
178   "  </array>\n"
179   "</dict>\n"
180   "</plist>\n";
181
182 static void inferior_debug (int level, const char *fmt, ...)
183   ATTRIBUTE_PRINTF (2, 3);
184
185 static void
186 inferior_debug (int level, const char *fmt, ...)
187 {
188   va_list ap;
189
190   if (darwin_debug_flag < level)
191     return;
192
193   va_start (ap, fmt);
194   printf_unfiltered (_("[%d inferior]: "), getpid ());
195   vprintf_unfiltered (fmt, ap);
196   va_end (ap);
197 }
198
199 void
200 mach_check_error (kern_return_t ret, const char *file,
201                   unsigned int line, const char *func)
202 {
203   if (ret == KERN_SUCCESS)
204     return;
205   if (func == NULL)
206     func = _("[UNKNOWN]");
207
208   warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
209            file, line, func, mach_error_string (ret), (unsigned long) ret);
210 }
211
212 static const char *
213 unparse_exception_type (unsigned int i)
214 {
215   static char unknown_exception_buf[32];
216
217   switch (i)
218     {
219     case EXC_BAD_ACCESS:
220       return "EXC_BAD_ACCESS";
221     case EXC_BAD_INSTRUCTION:
222       return "EXC_BAD_INSTRUCTION";
223     case EXC_ARITHMETIC:
224       return "EXC_ARITHMETIC";
225     case EXC_EMULATION:
226       return "EXC_EMULATION";
227     case EXC_SOFTWARE:
228       return "EXC_SOFTWARE";
229     case EXC_BREAKPOINT:
230       return "EXC_BREAKPOINT";
231     case EXC_SYSCALL:
232       return "EXC_SYSCALL";
233     case EXC_MACH_SYSCALL:
234       return "EXC_MACH_SYSCALL";
235     case EXC_RPC_ALERT:
236       return "EXC_RPC_ALERT";
237     case EXC_CRASH:
238       return "EXC_CRASH";
239     default:
240       snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
241       return unknown_exception_buf;
242     }
243 }
244
245 /* Set errno to zero, and then call ptrace with the given arguments.
246    If inferior debugging traces are on, then also print a debug
247    trace.
248
249    The returned value is the same as the value returned by ptrace,
250    except in the case where that value is -1 but errno is zero.
251    This case is documented to be a non-error situation, so we
252    return zero in that case. */
253
254 static int
255 darwin_ptrace (const char *name,
256                int request, int pid, caddr_t arg3, int arg4)
257 {
258   int ret;
259
260   errno = 0;
261   ret = ptrace (request, pid, arg3, arg4);
262   if (ret == -1 && errno == 0)
263     ret = 0;
264
265   inferior_debug (4, _("ptrace (%s, %d, 0x%lx, %d): %d (%s)\n"),
266                   name, pid, (unsigned long) arg3, arg4, ret,
267                   (ret != 0) ? safe_strerror (errno) : _("no error"));
268   return ret;
269 }
270
271 static int
272 cmp_thread_t (const void *l, const void *r)
273 {
274   thread_t tl = *(const thread_t *)l;
275   thread_t tr = *(const thread_t *)r;
276   return (int)(tl - tr);
277 }
278
279 static void
280 darwin_check_new_threads (struct inferior *inf)
281 {
282   kern_return_t kret;
283   unsigned int i;
284   thread_array_t thread_list;
285   unsigned int new_nbr;
286   unsigned int old_nbr;
287   unsigned int new_ix, old_ix;
288   darwin_inferior *darwin_inf = inf->priv;
289   VEC (darwin_thread_t) *thread_vec;
290
291   /* Get list of threads.  */
292   kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
293   MACH_CHECK_ERROR (kret);
294   if (kret != KERN_SUCCESS)
295     return;
296
297   /* Sort the list.  */
298   if (new_nbr > 1)
299     qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
300
301   if (darwin_inf->threads)
302     old_nbr = VEC_length (darwin_thread_t, darwin_inf->threads);
303   else
304     old_nbr = 0;
305
306   /* Quick check for no changes.  */
307   if (old_nbr == new_nbr)
308     {
309       for (i = 0; i < new_nbr; i++)
310         if (thread_list[i]
311             != VEC_index (darwin_thread_t, darwin_inf->threads, i)->gdb_port)
312           break;
313       if (i == new_nbr)
314         {
315           /* Deallocate ports.  */
316           for (i = 0; i < new_nbr; i++)
317             {
318               kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
319               MACH_CHECK_ERROR (kret);
320             }
321
322           /* Deallocate the buffer.  */
323           kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
324                                 new_nbr * sizeof (int));
325           MACH_CHECK_ERROR (kret);
326
327           return;
328         }
329     }
330
331   /* Full handling: detect new threads, remove dead threads.  */
332   thread_vec = VEC_alloc (darwin_thread_t, new_nbr);
333
334   for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
335     {
336       thread_t new_id = (new_ix < new_nbr) ?
337         thread_list[new_ix] : THREAD_NULL;
338       darwin_thread_t *old = (old_ix < old_nbr) ?
339         VEC_index (darwin_thread_t, darwin_inf->threads, old_ix) : NULL;
340       thread_t old_id = old ? old->gdb_port : THREAD_NULL;
341
342       inferior_debug
343         (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
344          new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
345
346       if (old_id == new_id)
347         {
348           /* Thread still exist.  */
349           VEC_safe_push (darwin_thread_t, thread_vec, old);
350           new_ix++;
351           old_ix++;
352
353           /* Deallocate the port.  */
354           kret = mach_port_deallocate (gdb_task, new_id);
355           MACH_CHECK_ERROR (kret);
356
357           continue;
358         }
359       if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
360         {
361           /* Ignore dead ports.
362              In some weird cases, we might get dead ports.  They should
363              correspond to dead thread so they could safely be ignored.  */
364           new_ix++;
365           continue;
366         }
367       if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
368         {
369           /* A thread was created.  */
370           struct private_thread_info *pti;
371
372           pti = XCNEW (struct private_thread_info);
373           pti->gdb_port = new_id;
374           pti->msg_state = DARWIN_RUNNING;
375
376           /* Add the new thread.  */
377           add_thread_with_info (ptid_build (inf->pid, 0, new_id), pti);
378           VEC_safe_push (darwin_thread_t, thread_vec, pti);
379           new_ix++;
380           continue;
381         }
382       if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
383         {
384           /* A thread was removed.  */
385           delete_thread (ptid_build (inf->pid, 0, old_id));
386           kret = mach_port_deallocate (gdb_task, old_id);
387           MACH_CHECK_ERROR (kret);
388           old_ix++;
389           continue;
390         }
391       gdb_assert_not_reached ("unexpected thread case");
392     }
393
394   if (darwin_inf->threads)
395     VEC_free (darwin_thread_t, darwin_inf->threads);
396   darwin_inf->threads = thread_vec;
397
398   /* Deallocate the buffer.  */
399   kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
400                         new_nbr * sizeof (int));
401   MACH_CHECK_ERROR (kret);
402 }
403
404 static int
405 find_inferior_task_it (struct inferior *inf, void *port_ptr)
406 {
407   return inf->priv->task == *(task_t *)port_ptr;
408 }
409
410 static int
411 find_inferior_pid_it (struct inferior *inf, void *pid_ptr)
412 {
413   return inf->pid == *(int *)pid_ptr;
414 }
415
416 /* Return an inferior by task port.  */
417 static struct inferior *
418 darwin_find_inferior_by_task (task_t port)
419 {
420   return iterate_over_inferiors (&find_inferior_task_it, &port);
421 }
422
423 /* Return an inferior by pid port.  */
424 static struct inferior *
425 darwin_find_inferior_by_pid (int pid)
426 {
427   return iterate_over_inferiors (&find_inferior_pid_it, &pid);
428 }
429
430 /* Return a thread by port.  */
431 static darwin_thread_t *
432 darwin_find_thread (struct inferior *inf, thread_t thread)
433 {
434   darwin_thread_t *t;
435   int k;
436
437   for (k = 0;
438        VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
439        k++)
440     if (t->gdb_port == thread)
441       return t;
442   return NULL;
443 }
444
445 /* Suspend (ie stop) an inferior at Mach level.  */
446
447 static void
448 darwin_suspend_inferior (struct inferior *inf)
449 {
450   if (!inf->priv->suspended)
451     {
452       kern_return_t kret;
453
454       kret = task_suspend (inf->priv->task);
455       MACH_CHECK_ERROR (kret);
456
457       inf->priv->suspended = 1;
458     }
459 }
460
461 /* Resume an inferior at Mach level.  */
462
463 static void
464 darwin_resume_inferior (struct inferior *inf)
465 {
466   if (inf->priv->suspended)
467     {
468       kern_return_t kret;
469
470       kret = task_resume (inf->priv->task);
471       MACH_CHECK_ERROR (kret);
472
473       inf->priv->suspended = 0;
474     }
475 }
476
477 /* Iterator functions.  */
478
479 static int
480 darwin_suspend_inferior_it (struct inferior *inf, void *arg)
481 {
482   darwin_suspend_inferior (inf);
483   darwin_check_new_threads (inf);
484   return 0;
485 }
486
487 static int
488 darwin_resume_inferior_it (struct inferior *inf, void *arg)
489 {
490   darwin_resume_inferior (inf);
491   return 0;
492 }
493
494 static void
495 darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
496 {
497   printf_unfiltered (_("message header:\n"));
498   printf_unfiltered (_(" bits: 0x%x\n"), hdr->msgh_bits);
499   printf_unfiltered (_(" size: 0x%x\n"), hdr->msgh_size);
500   printf_unfiltered (_(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
501   printf_unfiltered (_(" local-port: 0x%x\n"), hdr->msgh_local_port);
502   printf_unfiltered (_(" reserved: 0x%x\n"), hdr->msgh_reserved);
503   printf_unfiltered (_(" id: 0x%x\n"), hdr->msgh_id);
504
505   if (disp_body)
506     {
507       const unsigned char *data;
508       const unsigned int *ldata;
509       int size;
510       int i;
511
512       data = (unsigned char *)(hdr + 1);
513       size = hdr->msgh_size - sizeof (mach_msg_header_t);
514
515       if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
516         {
517           mach_msg_body_t *bod = (mach_msg_body_t*)data;
518           mach_msg_port_descriptor_t *desc =
519             (mach_msg_port_descriptor_t *)(bod + 1);
520           int k;
521           NDR_record_t *ndr;
522           printf_unfiltered (_("body: descriptor_count=%u\n"),
523                              bod->msgh_descriptor_count);
524           data += sizeof (mach_msg_body_t);
525           size -= sizeof (mach_msg_body_t);
526           for (k = 0; k < bod->msgh_descriptor_count; k++)
527             switch (desc[k].type)
528               {
529               case MACH_MSG_PORT_DESCRIPTOR:
530                 printf_unfiltered
531                   (_(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
532                    k, desc[k].type, desc[k].name, desc[k].disposition);
533                 break;
534               default:
535                 printf_unfiltered (_(" descr %d: type=%u\n"),
536                                    k, desc[k].type);
537                 break;
538               }
539           data += bod->msgh_descriptor_count
540             * sizeof (mach_msg_port_descriptor_t);
541           size -= bod->msgh_descriptor_count
542             * sizeof (mach_msg_port_descriptor_t);
543           ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
544           printf_unfiltered
545             (_("NDR: mig=%02x if=%02x encod=%02x "
546                "int=%02x char=%02x float=%02x\n"),
547              ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
548              ndr->int_rep, ndr->char_rep, ndr->float_rep);
549           data += sizeof (NDR_record_t);
550           size -= sizeof (NDR_record_t);
551         }
552
553       printf_unfiltered (_("  data:"));
554       ldata = (const unsigned int *)data;
555       for (i = 0; i < size / sizeof (unsigned int); i++)
556         printf_unfiltered (" %08x", ldata[i]);
557       printf_unfiltered (_("\n"));
558     }
559 }
560
561 /* Adjust inferior data when a new task was created.  */
562
563 static struct inferior *
564 darwin_find_new_inferior (task_t task_port, thread_t thread_port)
565 {
566   int task_pid;
567   struct inferior *inf;
568   kern_return_t kret;
569   mach_port_t prev;
570
571   /* Find the corresponding pid.  */
572   kret = pid_for_task (task_port, &task_pid);
573   if (kret != KERN_SUCCESS)
574     {
575       MACH_CHECK_ERROR (kret);
576       return NULL;
577     }
578
579   /* Find the inferior for this pid.  */
580   inf = darwin_find_inferior_by_pid (task_pid);
581   if (inf == NULL)
582     return NULL;
583
584   /* Deallocate saved exception ports.  */
585   darwin_deallocate_exception_ports (inf->priv);
586
587   /* No need to remove dead_name notification, but still...  */
588   kret = mach_port_request_notification (gdb_task, inf->priv->task,
589                                          MACH_NOTIFY_DEAD_NAME, 0,
590                                          MACH_PORT_NULL,
591                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
592                                          &prev);
593   if (kret != KERN_INVALID_ARGUMENT)
594     MACH_CHECK_ERROR (kret);
595
596   /* Replace old task port.  */
597   kret = mach_port_deallocate (gdb_task, inf->priv->task);
598   MACH_CHECK_ERROR (kret);
599   inf->priv->task = task_port;
600
601   darwin_setup_request_notification (inf);
602   darwin_setup_exceptions (inf);
603
604   return inf;
605 }
606
607 /* Check data representation.  */
608
609 static int
610 darwin_check_message_ndr (NDR_record_t *ndr)
611 {
612   if (ndr->mig_vers != NDR_PROTOCOL_2_0
613       || ndr->if_vers != NDR_PROTOCOL_2_0
614       || ndr->mig_encoding != NDR_record.mig_encoding
615       || ndr->int_rep != NDR_record.int_rep
616       || ndr->char_rep != NDR_record.char_rep
617       || ndr->float_rep != NDR_record.float_rep)
618     return -1;
619   return 0;
620 }
621
622 /* Decode an exception message.  */
623
624 static int
625 darwin_decode_exception_message (mach_msg_header_t *hdr,
626                                  struct inferior **pinf,
627                                  darwin_thread_t **pthread)
628 {
629   mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
630   mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
631   NDR_record_t *ndr;
632   integer_t *data;
633   struct inferior *inf;
634   darwin_thread_t *thread;
635   task_t task_port;
636   thread_t thread_port;
637   kern_return_t kret;
638   int i;
639
640   /* Check message destination.  */
641   if (hdr->msgh_local_port != darwin_ex_port)
642     return -1;
643
644   /* Check message header.  */
645   if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
646     return -1;
647
648   /* Check descriptors.  */
649   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
650                         + sizeof (*ndr) + 2 * sizeof (integer_t))
651       || bod->msgh_descriptor_count != 2
652       || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
653       || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
654       || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
655       || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
656     return -1;
657
658   /* Check data representation.  */
659   ndr = (NDR_record_t *)(desc + 2);
660   if (darwin_check_message_ndr (ndr) != 0)
661     return -1;
662
663   /* Ok, the hard work.  */
664   data = (integer_t *)(ndr + 1);
665
666   task_port = desc[1].name;
667   thread_port = desc[0].name;
668
669   /* Find process by port.  */
670   inf = darwin_find_inferior_by_task (task_port);
671   *pinf = inf;
672
673   if (inf == NULL && data[0] == EXC_SOFTWARE && data[1] == 2
674       && data[2] == EXC_SOFT_SIGNAL && data[3] == SIGTRAP)
675     {
676       /* Not a known inferior, but a sigtrap.  This happens on darwin 16.1.0,
677          as a new Mach task is created when a process exec.  */
678       inf = darwin_find_new_inferior (task_port, thread_port);
679       *pinf = inf;
680
681       if (inf == NULL)
682         {
683           /* Deallocate task_port, unless it was saved.  */
684           kret = mach_port_deallocate (mach_task_self (), task_port);
685           MACH_CHECK_ERROR (kret);
686         }
687     }
688   else
689     {
690       /* We got new rights to the task, get rid of it.  Do not get rid of
691          thread right, as we will need it to find the thread.  */
692       kret = mach_port_deallocate (mach_task_self (), task_port);
693       MACH_CHECK_ERROR (kret);
694     }
695
696   if (inf == NULL)
697     {
698       /* Not a known inferior.  This could happen if the child fork, as
699          the created process will inherit its exception port.
700          FIXME: should the exception port be restored ?  */
701       kern_return_t kret;
702       mig_reply_error_t reply;
703
704       inferior_debug
705         (4, _("darwin_decode_exception_message: unknown task 0x%x\n"),
706          task_port);
707
708       /* Free thread port (we don't know it).  */
709       kret = mach_port_deallocate (mach_task_self (), thread_port);
710       MACH_CHECK_ERROR (kret);
711
712       darwin_encode_reply (&reply, hdr, KERN_SUCCESS);
713
714       kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
715                        reply.Head.msgh_size, 0,
716                        MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
717                        MACH_PORT_NULL);
718       MACH_CHECK_ERROR (kret);
719
720       return 0;
721     }
722
723   /* Find thread by port.  */
724   /* Check for new threads.  Do it early so that the port in the exception
725      message can be deallocated.  */
726   darwin_check_new_threads (inf);
727
728   /* Free the thread port (as gdb knows the thread, it has already has a right
729      for it, so this just decrement a reference counter).  */
730   kret = mach_port_deallocate (mach_task_self (), thread_port);
731   MACH_CHECK_ERROR (kret);
732
733   thread = darwin_find_thread (inf, thread_port);
734   if (thread == NULL)
735     return -1;
736   *pthread = thread;
737
738   /* The thread should be running.  However we have observed cases where a
739      thread got a SIGTTIN message after being stopped.  */
740   gdb_assert (thread->msg_state != DARWIN_MESSAGE);
741
742   /* Finish decoding.  */
743   thread->event.header = *hdr;
744   thread->event.thread_port = thread_port;
745   thread->event.task_port = task_port;
746   thread->event.ex_type = data[0];
747   thread->event.data_count = data[1];
748
749   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
750                         + sizeof (*ndr) + 2 * sizeof (integer_t)
751                         + data[1] * sizeof (integer_t)))
752       return -1;
753   for (i = 0; i < data[1]; i++)
754     thread->event.ex_data[i] = data[2 + i];
755
756   thread->msg_state = DARWIN_MESSAGE;
757
758   return 0;
759 }
760
761 /* Decode dead_name notify message.  */
762
763 static int
764 darwin_decode_notify_message (mach_msg_header_t *hdr, struct inferior **pinf)
765 {
766   NDR_record_t *ndr = (NDR_record_t *)(hdr + 1);
767   integer_t *data = (integer_t *)(ndr + 1);
768   struct inferior *inf;
769   darwin_thread_t *thread;
770   task_t task_port;
771   thread_t thread_port;
772   kern_return_t kret;
773   int i;
774
775   /* Check message header.  */
776   if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
777     return -1;
778
779   /* Check descriptors.  */
780   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*ndr) + sizeof (integer_t)))
781     return -2;
782
783   /* Check data representation.  */
784   if (darwin_check_message_ndr (ndr) != 0)
785     return -3;
786
787   task_port = data[0];
788
789   /* Find process by port.  */
790   inf = darwin_find_inferior_by_task (task_port);
791   *pinf = inf;
792
793   /* Check message destination.  */
794   if (inf != NULL && hdr->msgh_local_port != inf->priv->notify_port)
795     return -4;
796
797   return 0;
798 }
799
800 static void
801 darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
802                      integer_t code)
803 {
804   mach_msg_header_t *rh = &reply->Head;
805
806   rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
807   rh->msgh_remote_port = hdr->msgh_remote_port;
808   rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
809   rh->msgh_local_port = MACH_PORT_NULL;
810   rh->msgh_id = hdr->msgh_id + 100;
811
812   reply->NDR = NDR_record;
813   reply->RetCode = code;
814 }
815
816 static void
817 darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
818 {
819   kern_return_t kret;
820   mig_reply_error_t reply;
821
822   darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
823
824   kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
825                    reply.Head.msgh_size, 0,
826                    MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
827                    MACH_PORT_NULL);
828   MACH_CHECK_ERROR (kret);
829
830   inf->priv->pending_messages--;
831 }
832
833 static void
834 darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
835                       int step, int nsignal)
836 {
837   kern_return_t kret;
838   int res;
839
840   inferior_debug
841     (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
842      thread->msg_state, thread->gdb_port, step, nsignal);
843
844   switch (thread->msg_state)
845     {
846     case DARWIN_MESSAGE:
847       if (thread->event.ex_type == EXC_SOFTWARE
848           && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
849         {
850           /* Either deliver a new signal or cancel the signal received.  */
851           res = PTRACE (PT_THUPDATE, inf->pid,
852                         (caddr_t) (uintptr_t) thread->gdb_port, nsignal);
853           if (res < 0)
854             inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
855         }
856       else if (nsignal)
857         {
858           /* Note: ptrace is allowed only if the process is stopped.
859              Directly send the signal to the thread.  */
860           res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
861           inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
862                           thread->gdb_port, nsignal, res);
863           thread->signaled = 1;
864         }
865
866       /* Set or reset single step.  */
867       inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
868                       thread->gdb_port, step);
869       darwin_set_sstep (thread->gdb_port, step);
870       thread->single_step = step;
871
872       darwin_send_reply (inf, thread);
873       thread->msg_state = DARWIN_RUNNING;
874       break;
875
876     case DARWIN_RUNNING:
877       break;
878
879     case DARWIN_STOPPED:
880       kret = thread_resume (thread->gdb_port);
881       MACH_CHECK_ERROR (kret);
882
883       thread->msg_state = DARWIN_RUNNING;
884       break;
885     }
886 }
887
888 /* Resume all threads of the inferior.  */
889
890 static void
891 darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
892 {
893   darwin_thread_t *thread;
894   int k;
895
896   for (k = 0;
897        VEC_iterate (darwin_thread_t, inf->priv->threads, k, thread);
898        k++)
899     darwin_resume_thread (inf, thread, step, nsignal);
900 }
901
902 struct resume_inferior_threads_param
903 {
904   int step;
905   int nsignal;
906 };
907
908 static int
909 darwin_resume_inferior_threads_it (struct inferior *inf, void *param)
910 {
911   int step = ((struct resume_inferior_threads_param *)param)->step;
912   int nsignal = ((struct resume_inferior_threads_param *)param)->nsignal;
913
914   darwin_resume_inferior_threads (inf, step, nsignal);
915
916   return 0;
917 }
918
919 /* Suspend all threads of INF.  */
920
921 static void
922 darwin_suspend_inferior_threads (struct inferior *inf)
923 {
924   darwin_thread_t *thread;
925   kern_return_t kret;
926   int k;
927
928   for (k = 0;
929        VEC_iterate (darwin_thread_t, inf->priv->threads, k, thread);
930        k++)
931     switch (thread->msg_state)
932       {
933       case DARWIN_STOPPED:
934       case DARWIN_MESSAGE:
935         break;
936       case DARWIN_RUNNING:
937         kret = thread_suspend (thread->gdb_port);
938         MACH_CHECK_ERROR (kret);
939         thread->msg_state = DARWIN_STOPPED;
940         break;
941       }
942 }
943
944 static void
945 darwin_resume (ptid_t ptid, int step, enum gdb_signal signal)
946 {
947   struct target_waitstatus status;
948   int pid;
949
950   kern_return_t kret;
951   int res;
952   int nsignal;
953   struct inferior *inf;
954
955   inferior_debug
956     (2, _("darwin_resume: pid=%d, tid=0x%lx, step=%d, signal=%d\n"),
957      ptid_get_pid (ptid), ptid_get_tid (ptid), step, signal);
958
959   if (signal == GDB_SIGNAL_0)
960     nsignal = 0;
961   else
962     nsignal = gdb_signal_to_host (signal);
963
964   /* Don't try to single step all threads.  */
965   if (step)
966     ptid = inferior_ptid;
967
968   /* minus_one_ptid is RESUME_ALL.  */
969   if (ptid_equal (ptid, minus_one_ptid))
970     {
971       struct resume_inferior_threads_param param;
972
973       param.nsignal = nsignal;
974       param.step = step;
975
976       /* Resume threads.  */
977       iterate_over_inferiors (darwin_resume_inferior_threads_it, &param);
978       /* Resume tasks.  */
979       iterate_over_inferiors (darwin_resume_inferior_it, NULL);
980     }
981   else
982     {
983       struct inferior *inf = find_inferior_ptid (ptid);
984       long tid = ptid_get_tid (ptid);
985
986       /* Stop the inferior (should be useless).  */
987       darwin_suspend_inferior (inf);
988
989       if (tid == 0)
990         darwin_resume_inferior_threads (inf, step, nsignal);
991       else
992         {
993           darwin_thread_t *thread;
994
995           /* Suspend threads of the task.  */
996           darwin_suspend_inferior_threads (inf);
997
998           /* Resume the selected thread.  */
999           thread = darwin_find_thread (inf, tid);
1000           gdb_assert (thread);
1001           darwin_resume_thread (inf, thread, step, nsignal);
1002         }
1003
1004       /* Resume the task.  */
1005       darwin_resume_inferior (inf);
1006     }
1007 }
1008
1009 static void
1010 darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
1011                   enum gdb_signal signal)
1012 {
1013   return darwin_resume (ptid, step, signal);
1014 }
1015
1016 static ptid_t
1017 darwin_decode_message (mach_msg_header_t *hdr,
1018                        darwin_thread_t **pthread,
1019                        struct inferior **pinf,
1020                        struct target_waitstatus *status)
1021 {
1022   darwin_thread_t *thread;
1023   struct inferior *inf;
1024
1025   /* Exception message.  2401 == 0x961 is exc.  */
1026   if (hdr->msgh_id == 2401)
1027     {
1028       int res;
1029
1030       /* Decode message.  */
1031       res = darwin_decode_exception_message (hdr, &inf, &thread);
1032
1033       if (res < 0)
1034         {
1035           /* Should not happen...  */
1036           printf_unfiltered
1037             (_("darwin_wait: ill-formatted message (id=0x%x)\n"), hdr->msgh_id);
1038           /* FIXME: send a failure reply?  */
1039           status->kind = TARGET_WAITKIND_IGNORE;
1040           return minus_one_ptid;
1041         }
1042       if (inf == NULL)
1043         {
1044           status->kind = TARGET_WAITKIND_IGNORE;
1045           return minus_one_ptid;
1046         }
1047       *pinf = inf;
1048       *pthread = thread;
1049       inf->priv->pending_messages++;
1050
1051       status->kind = TARGET_WAITKIND_STOPPED;
1052       thread->msg_state = DARWIN_MESSAGE;
1053
1054       inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
1055                       thread->gdb_port,
1056                       unparse_exception_type (thread->event.ex_type));
1057
1058       switch (thread->event.ex_type)
1059         {
1060         case EXC_BAD_ACCESS:
1061           status->value.sig = GDB_EXC_BAD_ACCESS;
1062           break;
1063         case EXC_BAD_INSTRUCTION:
1064           status->value.sig = GDB_EXC_BAD_INSTRUCTION;
1065           break;
1066         case EXC_ARITHMETIC:
1067           status->value.sig = GDB_EXC_ARITHMETIC;
1068           break;
1069         case EXC_EMULATION:
1070           status->value.sig = GDB_EXC_EMULATION;
1071           break;
1072         case EXC_SOFTWARE:
1073           if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
1074             {
1075               status->value.sig =
1076                 gdb_signal_from_host (thread->event.ex_data[1]);
1077               inferior_debug (5, _("  (signal %d: %s)\n"),
1078                               thread->event.ex_data[1],
1079                               gdb_signal_to_name (status->value.sig));
1080
1081               /* If the thread is stopped because it has received a signal
1082                  that gdb has just sent, continue.  */
1083               if (thread->signaled)
1084                 {
1085                   thread->signaled = 0;
1086                   darwin_send_reply (inf, thread);
1087                   thread->msg_state = DARWIN_RUNNING;
1088                   status->kind = TARGET_WAITKIND_IGNORE;
1089                 }
1090             }
1091           else
1092             status->value.sig = GDB_EXC_SOFTWARE;
1093           break;
1094         case EXC_BREAKPOINT:
1095           /* Many internal GDB routines expect breakpoints to be reported
1096              as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
1097              as a spurious signal.  */
1098           status->value.sig = GDB_SIGNAL_TRAP;
1099           break;
1100         default:
1101           status->value.sig = GDB_SIGNAL_UNKNOWN;
1102           break;
1103         }
1104
1105       return ptid_build (inf->pid, 0, thread->gdb_port);
1106     }
1107   else if (hdr->msgh_id == 0x48)
1108     {
1109       /* MACH_NOTIFY_DEAD_NAME: notification for exit.  */
1110       int res;
1111
1112       res = darwin_decode_notify_message (hdr, &inf);
1113
1114       if (res < 0)
1115         {
1116           /* Should not happen...  */
1117           printf_unfiltered
1118             (_("darwin_wait: ill-formatted message (id=0x%x, res=%d)\n"),
1119              hdr->msgh_id, res);
1120         }
1121
1122       *pinf = NULL;
1123       *pthread = NULL;
1124
1125       if (res < 0 || inf == NULL)
1126         {
1127           status->kind = TARGET_WAITKIND_IGNORE;
1128           return minus_one_ptid;
1129         }
1130
1131       if (inf != NULL)
1132         {
1133           if (!inf->priv->no_ptrace)
1134             {
1135               pid_t res;
1136               int wstatus;
1137
1138               res = wait4 (inf->pid, &wstatus, 0, NULL);
1139               if (res < 0 || res != inf->pid)
1140                 {
1141                   printf_unfiltered (_("wait4: res=%d: %s\n"),
1142                                      res, safe_strerror (errno));
1143                   status->kind = TARGET_WAITKIND_IGNORE;
1144                   return minus_one_ptid;
1145                 }
1146               if (WIFEXITED (wstatus))
1147                 {
1148                   status->kind = TARGET_WAITKIND_EXITED;
1149                   status->value.integer = WEXITSTATUS (wstatus);
1150                 }
1151               else
1152                 {
1153                   status->kind = TARGET_WAITKIND_SIGNALLED;
1154                   status->value.sig = gdb_signal_from_host (WTERMSIG (wstatus));
1155                 }
1156
1157               inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
1158                               res, wstatus);
1159
1160               /* Looks necessary on Leopard and harmless...  */
1161               wait4 (inf->pid, &wstatus, 0, NULL);
1162
1163               inferior_ptid = ptid_build (inf->pid, 0, 0);
1164               return inferior_ptid;
1165             }
1166           else
1167             {
1168               inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
1169               status->kind = TARGET_WAITKIND_EXITED;
1170               status->value.integer = 0; /* Don't know.  */
1171               return ptid_build (inf->pid, 0, 0);
1172             }
1173         }
1174     }
1175
1176   /* Unknown message.  */
1177   warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
1178   status->kind = TARGET_WAITKIND_IGNORE;
1179   return minus_one_ptid;
1180 }
1181
1182 static int
1183 cancel_breakpoint (ptid_t ptid)
1184 {
1185   /* Arrange for a breakpoint to be hit again later.  We will handle
1186      the current event, eventually we will resume this thread, and this
1187      breakpoint will trap again.
1188
1189      If we do not do this, then we run the risk that the user will
1190      delete or disable the breakpoint, but the thread will have already
1191      tripped on it.  */
1192
1193   struct regcache *regcache = get_thread_regcache (ptid);
1194   struct gdbarch *gdbarch = regcache->arch ();
1195   CORE_ADDR pc;
1196
1197   pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
1198   if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
1199     {
1200       inferior_debug (4, "cancel_breakpoint for thread 0x%lx\n",
1201                       (unsigned long) ptid_get_tid (ptid));
1202
1203       /* Back up the PC if necessary.  */
1204       if (gdbarch_decr_pc_after_break (gdbarch))
1205         regcache_write_pc (regcache, pc);
1206
1207       return 1;
1208     }
1209   return 0;
1210 }
1211
1212 static ptid_t
1213 darwin_wait (ptid_t ptid, struct target_waitstatus *status)
1214 {
1215   kern_return_t kret;
1216   union
1217   {
1218     mach_msg_header_t hdr;
1219     char data[0x100];
1220   } msgin;
1221   mach_msg_header_t *hdr = &msgin.hdr;
1222   ptid_t res;
1223   darwin_thread_t *thread;
1224   struct inferior *inf;
1225
1226   inferior_debug
1227     (2, _("darwin_wait: waiting for a message pid=%d thread=%lx\n"),
1228      ptid_get_pid (ptid), ptid_get_tid (ptid));
1229
1230   /* Handle fake stop events at first.  */
1231   if (darwin_inf_fake_stop != NULL)
1232     {
1233       inf = darwin_inf_fake_stop;
1234       darwin_inf_fake_stop = NULL;
1235
1236       status->kind = TARGET_WAITKIND_STOPPED;
1237       status->value.sig = GDB_SIGNAL_TRAP;
1238       thread = VEC_index (darwin_thread_t, inf->priv->threads, 0);
1239       thread->msg_state = DARWIN_STOPPED;
1240       return ptid_build (inf->pid, 0, thread->gdb_port);
1241     }
1242
1243   do
1244     {
1245       /* set_sigint_trap (); */
1246
1247       /* Wait for a message.  */
1248       kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1249                        sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1250
1251       /* clear_sigint_trap (); */
1252
1253       if (kret == MACH_RCV_INTERRUPTED)
1254         {
1255           status->kind = TARGET_WAITKIND_IGNORE;
1256           return minus_one_ptid;
1257         }
1258
1259       if (kret != MACH_MSG_SUCCESS)
1260         {
1261           inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
1262           status->kind = TARGET_WAITKIND_SPURIOUS;
1263           return minus_one_ptid;
1264         }
1265
1266       /* Debug: display message.  */
1267       if (darwin_debug_flag > 10)
1268         darwin_dump_message (hdr, darwin_debug_flag > 11);
1269
1270       res = darwin_decode_message (hdr, &thread, &inf, status);
1271       if (ptid_equal (res, minus_one_ptid))
1272         continue;
1273
1274       /* Early return in case an inferior has exited.  */
1275       if (inf == NULL)
1276         return res;
1277     }
1278   while (status->kind == TARGET_WAITKIND_IGNORE);
1279
1280   /* Stop all tasks.  */
1281   iterate_over_inferiors (darwin_suspend_inferior_it, NULL);
1282
1283   /* Read pending messages.  */
1284   while (1)
1285     {
1286       struct target_waitstatus status2;
1287       ptid_t ptid2;
1288
1289       kret = mach_msg (&msgin.hdr,
1290                        MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1291                        sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1292
1293       if (kret == MACH_RCV_TIMED_OUT)
1294         break;
1295       if (kret != MACH_MSG_SUCCESS)
1296         {
1297           inferior_debug
1298             (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
1299           break;
1300         }
1301
1302       /* Debug: display message.  */
1303       if (darwin_debug_flag > 10)
1304         darwin_dump_message (hdr, darwin_debug_flag > 11);
1305
1306       ptid2 = darwin_decode_message (hdr, &thread, &inf, &status2);
1307
1308       if (inf != NULL && thread != NULL
1309           && thread->event.ex_type == EXC_BREAKPOINT)
1310         {
1311           if (thread->single_step
1312               || cancel_breakpoint (ptid_build (inf->pid, 0, thread->gdb_port)))
1313             {
1314               gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1315               darwin_send_reply (inf, thread);
1316               thread->msg_state = DARWIN_RUNNING;
1317             }
1318           else
1319             inferior_debug
1320               (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
1321                thread->gdb_port);
1322         }
1323       else
1324         inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1325     }
1326   return res;
1327 }
1328
1329 static ptid_t
1330 darwin_wait_to (struct target_ops *ops,
1331                 ptid_t ptid, struct target_waitstatus *status, int options)
1332 {
1333   return darwin_wait (ptid, status);
1334 }
1335
1336 static void
1337 darwin_interrupt (struct target_ops *self, ptid_t t)
1338 {
1339   struct inferior *inf = current_inferior ();
1340
1341   /* FIXME: handle in no_ptrace mode.  */
1342   gdb_assert (!inf->priv->no_ptrace);
1343   kill (inf->pid, SIGINT);
1344 }
1345
1346 /* Deallocate threads port and vector.  */
1347
1348 static void
1349 darwin_deallocate_threads (struct inferior *inf)
1350 {
1351   if (inf->priv->threads)
1352     {
1353       kern_return_t kret;
1354       int k;
1355       darwin_thread_t *t;
1356       for (k = 0;
1357            VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
1358            k++)
1359         {
1360           kret = mach_port_deallocate (gdb_task, t->gdb_port);
1361           MACH_CHECK_ERROR (kret);
1362         }
1363       VEC_free (darwin_thread_t, inf->priv->threads);
1364       inf->priv->threads = NULL;
1365     }
1366 }
1367
1368 static void
1369 darwin_mourn_inferior (struct target_ops *ops)
1370 {
1371   struct inferior *inf = current_inferior ();
1372   kern_return_t kret;
1373   mach_port_t prev;
1374   int i;
1375
1376   /* Deallocate threads.  */
1377   darwin_deallocate_threads (inf);
1378
1379   /* Remove notify_port from darwin_port_set.  */
1380   kret = mach_port_move_member (gdb_task,
1381                                 inf->priv->notify_port, MACH_PORT_NULL);
1382   MACH_CHECK_ERROR (kret);
1383
1384   /* Remove task port dead_name notification.  */
1385   kret = mach_port_request_notification (gdb_task, inf->priv->task,
1386                                          MACH_NOTIFY_DEAD_NAME, 0,
1387                                          MACH_PORT_NULL,
1388                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
1389                                          &prev);
1390   /* This can fail if the task is dead.  */
1391   inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
1392                   inf->priv->task, prev, inf->priv->notify_port);
1393
1394   if (kret == KERN_SUCCESS)
1395     {
1396       kret = mach_port_deallocate (gdb_task, prev);
1397       MACH_CHECK_ERROR (kret);
1398     }
1399
1400   /* Destroy notify_port.  */
1401   kret = mach_port_destroy (gdb_task, inf->priv->notify_port);
1402   MACH_CHECK_ERROR (kret);
1403
1404   /* Deallocate saved exception ports.  */
1405   darwin_deallocate_exception_ports (inf->priv);
1406
1407   /* Deallocate task port.  */
1408   kret = mach_port_deallocate (gdb_task, inf->priv->task);
1409   MACH_CHECK_ERROR (kret);
1410
1411   xfree (inf->priv);
1412   inf->priv = NULL;
1413
1414   inf_child_mourn_inferior (ops);
1415 }
1416
1417 static void
1418 darwin_reply_to_all_pending_messages (struct inferior *inf)
1419 {
1420   int k;
1421   darwin_thread_t *t;
1422
1423   for (k = 0;
1424        VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
1425        k++)
1426     {
1427       if (t->msg_state == DARWIN_MESSAGE)
1428         darwin_resume_thread (inf, t, 0, 0);
1429     }
1430 }
1431
1432 static void
1433 darwin_stop_inferior (struct inferior *inf)
1434 {
1435   struct target_waitstatus wstatus;
1436   ptid_t ptid;
1437   kern_return_t kret;
1438   int status;
1439   int res;
1440
1441   gdb_assert (inf != NULL);
1442
1443   darwin_suspend_inferior (inf);
1444
1445   darwin_reply_to_all_pending_messages (inf);
1446
1447   if (inf->priv->no_ptrace)
1448     return;
1449
1450   res = kill (inf->pid, SIGSTOP);
1451   if (res != 0)
1452     warning (_("cannot kill: %s"), safe_strerror (errno));
1453
1454   /* Wait until the process is really stopped.  */
1455   while (1)
1456     {
1457       ptid = darwin_wait (inferior_ptid, &wstatus);
1458       if (wstatus.kind == TARGET_WAITKIND_STOPPED
1459           && wstatus.value.sig == GDB_SIGNAL_STOP)
1460         break;
1461     }
1462 }
1463
1464 static kern_return_t
1465 darwin_save_exception_ports (darwin_inferior *inf)
1466 {
1467   kern_return_t kret;
1468
1469   inf->exception_info.count =
1470     sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1471
1472   kret = task_get_exception_ports
1473     (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1474      &inf->exception_info.count, inf->exception_info.ports,
1475      inf->exception_info.behaviors, inf->exception_info.flavors);
1476   return kret;
1477 }
1478
1479 static kern_return_t
1480 darwin_restore_exception_ports (darwin_inferior *inf)
1481 {
1482   int i;
1483   kern_return_t kret;
1484
1485   for (i = 0; i < inf->exception_info.count; i++)
1486     {
1487       kret = task_set_exception_ports
1488         (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1489          inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1490       if (kret != KERN_SUCCESS)
1491         return kret;
1492     }
1493
1494   return KERN_SUCCESS;
1495 }
1496
1497 /* Deallocate saved exception ports.  */
1498
1499 static void
1500 darwin_deallocate_exception_ports (darwin_inferior *inf)
1501 {
1502   int i;
1503   kern_return_t kret;
1504
1505   for (i = 0; i < inf->exception_info.count; i++)
1506     {
1507       kret = mach_port_deallocate (gdb_task, inf->exception_info.ports[i]);
1508       MACH_CHECK_ERROR (kret);
1509     }
1510   inf->exception_info.count = 0;
1511 }
1512
1513 static void
1514 darwin_setup_exceptions (struct inferior *inf)
1515 {
1516   kern_return_t kret;
1517   int traps_expected;
1518   exception_mask_t mask;
1519
1520   kret = darwin_save_exception_ports (inf->priv);
1521   if (kret != KERN_SUCCESS)
1522     error (_("Unable to save exception ports, task_get_exception_ports"
1523              "returned: %d"),
1524            kret);
1525
1526   /* Set exception port.  */
1527   if (enable_mach_exceptions)
1528     mask = EXC_MASK_ALL;
1529   else
1530     mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1531   kret = task_set_exception_ports (inf->priv->task, mask, darwin_ex_port,
1532                                    EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1533   if (kret != KERN_SUCCESS)
1534     error (_("Unable to set exception ports, task_set_exception_ports"
1535              "returned: %d"),
1536            kret);
1537 }
1538
1539 static void
1540 darwin_kill_inferior (struct target_ops *ops)
1541 {
1542   struct inferior *inf = current_inferior ();
1543   struct target_waitstatus wstatus;
1544   ptid_t ptid;
1545   kern_return_t kret;
1546   int status;
1547   int res;
1548
1549   if (ptid_equal (inferior_ptid, null_ptid))
1550     return;
1551
1552   gdb_assert (inf != NULL);
1553
1554   kret = darwin_restore_exception_ports (inf->priv);
1555   MACH_CHECK_ERROR (kret);
1556
1557   darwin_reply_to_all_pending_messages (inf);
1558
1559   res = kill (inf->pid, 9);
1560
1561   if (res == 0)
1562     {
1563       darwin_resume_inferior (inf);
1564
1565       ptid = darwin_wait (inferior_ptid, &wstatus);
1566     }
1567   else if (errno != ESRCH)
1568     warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
1569              inf->pid, safe_strerror (errno));
1570
1571   target_mourn_inferior (inferior_ptid);
1572 }
1573
1574 static void
1575 darwin_setup_request_notification (struct inferior *inf)
1576 {
1577   kern_return_t kret;
1578   mach_port_t prev_not;
1579
1580   kret = mach_port_request_notification (gdb_task, inf->priv->task,
1581                                          MACH_NOTIFY_DEAD_NAME, 0,
1582                                          inf->priv->notify_port,
1583                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
1584                                          &prev_not);
1585   if (kret != KERN_SUCCESS)
1586     error (_("Termination notification request failed, "
1587              "mach_port_request_notification\n"
1588              "returned: %d"),
1589            kret);
1590   if (prev_not != MACH_PORT_NULL)
1591     {
1592       /* This is unexpected, as there should not be any previously
1593          registered notification request.  But this is not a fatal
1594          issue, so just emit a warning.  */
1595       warning (_("\
1596 A task termination request was registered before the debugger registered\n\
1597 its own.  This is unexpected, but should otherwise not have any actual\n\
1598 impact on the debugging session."));
1599     }
1600 }
1601
1602 static void
1603 darwin_attach_pid (struct inferior *inf)
1604 {
1605   kern_return_t kret;
1606   mach_port_t prev_port;
1607   int traps_expected;
1608   mach_port_t prev_not;
1609   exception_mask_t mask;
1610
1611   inf->priv = XCNEW (darwin_inferior);
1612
1613   kret = task_for_pid (gdb_task, inf->pid, &inf->priv->task);
1614   if (kret != KERN_SUCCESS)
1615     {
1616       int status;
1617
1618       if (!inf->attach_flag)
1619         {
1620           kill (inf->pid, 9);
1621           waitpid (inf->pid, &status, 0);
1622         }
1623
1624       error (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
1625                " (please check gdb is codesigned - see taskgated(8))"),
1626              inf->pid, mach_error_string (kret), (unsigned long) kret);
1627     }
1628
1629   inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1630                   inf->priv->task, inf->pid);
1631
1632   if (darwin_ex_port == MACH_PORT_NULL)
1633     {
1634       /* Create a port to get exceptions.  */
1635       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1636                                  &darwin_ex_port);
1637       if (kret != KERN_SUCCESS)
1638         error (_("Unable to create exception port, mach_port_allocate "
1639                  "returned: %d"),
1640                kret);
1641
1642       kret = mach_port_insert_right (gdb_task, darwin_ex_port, darwin_ex_port,
1643                                      MACH_MSG_TYPE_MAKE_SEND);
1644       if (kret != KERN_SUCCESS)
1645         error (_("Unable to create exception port, mach_port_insert_right "
1646                  "returned: %d"),
1647                kret);
1648
1649       /* Create a port set and put ex_port in it.  */
1650       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1651                                  &darwin_port_set);
1652       if (kret != KERN_SUCCESS)
1653         error (_("Unable to create port set, mach_port_allocate "
1654                  "returned: %d"),
1655                kret);
1656
1657       kret = mach_port_move_member (gdb_task, darwin_ex_port, darwin_port_set);
1658       if (kret != KERN_SUCCESS)
1659         error (_("Unable to move exception port into new port set, "
1660                  "mach_port_move_member\n"
1661                  "returned: %d"),
1662                kret);
1663     }
1664
1665   /* Create a port to be notified when the child task terminates.  */
1666   kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1667                              &inf->priv->notify_port);
1668   if (kret != KERN_SUCCESS)
1669     error (_("Unable to create notification port, mach_port_allocate "
1670              "returned: %d"),
1671            kret);
1672
1673   kret = mach_port_move_member (gdb_task,
1674                                 inf->priv->notify_port, darwin_port_set);
1675   if (kret != KERN_SUCCESS)
1676     error (_("Unable to move notification port into new port set, "
1677              "mach_port_move_member\n"
1678              "returned: %d"),
1679            kret);
1680
1681   darwin_setup_request_notification (inf);
1682
1683   darwin_setup_exceptions (inf);
1684
1685   if (!target_is_pushed (darwin_ops))
1686     push_target (darwin_ops);
1687 }
1688
1689 /* Get the thread_info object corresponding to this private_thread_info.  */
1690
1691 static struct thread_info *
1692 thread_info_from_private_thread_info (private_thread_info *pti)
1693 {
1694   struct thread_info *it;
1695
1696   ALL_THREADS (it)
1697     {
1698       if (it->priv->gdb_port == pti->gdb_port)
1699         break;
1700     }
1701
1702   gdb_assert (it != NULL);
1703
1704   return it;
1705 }
1706
1707 static void
1708 darwin_init_thread_list (struct inferior *inf)
1709 {
1710   darwin_check_new_threads (inf);
1711
1712   gdb_assert (inf->priv->threads != NULL);
1713   gdb_assert (VEC_length (darwin_thread_t, inf->priv->threads) > 0);
1714
1715   private_thread_info *first_pti
1716     = VEC_index (darwin_thread_t, inf->priv->threads, 0);
1717   struct thread_info *first_thread
1718     = thread_info_from_private_thread_info (first_pti);
1719
1720   inferior_ptid = first_thread->ptid;
1721 }
1722
1723 /* The child must synchronize with gdb: gdb must set the exception port
1724    before the child call PTRACE_SIGEXC.  We use a pipe to achieve this.
1725    FIXME: is there a lighter way ?  */
1726 static int ptrace_fds[2];
1727
1728 static void
1729 darwin_ptrace_me (void)
1730 {
1731   int res;
1732   char c;
1733
1734   /* Close write end point.  */
1735   if (close (ptrace_fds[1]) < 0)
1736     trace_start_error_with_name ("close");
1737
1738   /* Wait until gdb is ready.  */
1739   res = read (ptrace_fds[0], &c, 1);
1740   if (res != 0)
1741     trace_start_error (_("unable to read from pipe, read returned: %d"), res);
1742
1743   if (close (ptrace_fds[0]) < 0)
1744     trace_start_error_with_name ("close");
1745
1746   /* Get rid of privileges.  */
1747   if (setegid (getgid ()) < 0)
1748     trace_start_error_with_name ("setegid");
1749
1750   /* Set TRACEME.  */
1751   if (PTRACE (PT_TRACE_ME, 0, 0, 0) < 0)
1752     trace_start_error_with_name ("PTRACE");
1753
1754   /* Redirect signals to exception port.  */
1755   if (PTRACE (PT_SIGEXC, 0, 0, 0) < 0)
1756     trace_start_error_with_name ("PTRACE");
1757 }
1758
1759 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).  */
1760 static void
1761 darwin_pre_ptrace (void)
1762 {
1763   if (pipe (ptrace_fds) != 0)
1764     {
1765       ptrace_fds[0] = -1;
1766       ptrace_fds[1] = -1;
1767       error (_("unable to create a pipe: %s"), safe_strerror (errno));
1768     }
1769
1770   mark_fd_no_cloexec (ptrace_fds[0]);
1771   mark_fd_no_cloexec (ptrace_fds[1]);
1772 }
1773
1774 static void
1775 darwin_ptrace_him (int pid)
1776 {
1777   task_t itask;
1778   kern_return_t kret;
1779   mach_port_t prev_port;
1780   int traps_expected;
1781   struct inferior *inf = current_inferior ();
1782
1783   darwin_attach_pid (inf);
1784
1785   /* Let's the child run.  */
1786   close (ptrace_fds[0]);
1787   close (ptrace_fds[1]);
1788
1789   unmark_fd_no_cloexec (ptrace_fds[0]);
1790   unmark_fd_no_cloexec (ptrace_fds[1]);
1791
1792   darwin_init_thread_list (inf);
1793
1794   gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
1795 }
1796
1797 static void
1798 darwin_execvp (const char *file, char * const argv[], char * const env[])
1799 {
1800   posix_spawnattr_t attr;
1801   short ps_flags = 0;
1802   int res;
1803
1804   res = posix_spawnattr_init (&attr);
1805   if (res != 0)
1806     {
1807       fprintf_unfiltered
1808         (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
1809       return;
1810     }
1811
1812   /* Do like execve: replace the image.  */
1813   ps_flags = POSIX_SPAWN_SETEXEC;
1814
1815   /* Disable ASLR.  The constant doesn't look to be available outside the
1816      kernel include files.  */
1817 #ifndef _POSIX_SPAWN_DISABLE_ASLR
1818 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
1819 #endif
1820   ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
1821   res = posix_spawnattr_setflags (&attr, ps_flags);
1822   if (res != 0)
1823     {
1824       fprintf_unfiltered (gdb_stderr, "Cannot set posix_spawn flags\n");
1825       return;
1826     }
1827
1828   posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
1829 }
1830
1831 static void
1832 darwin_create_inferior (struct target_ops *ops,
1833                         const char *exec_file,
1834                         const std::string &allargs,
1835                         char **env, int from_tty)
1836 {
1837   /* Do the hard work.  */
1838   fork_inferior (exec_file, allargs, env, darwin_ptrace_me,
1839                  darwin_ptrace_him, darwin_pre_ptrace, NULL,
1840                  darwin_execvp);
1841 }
1842 \f
1843
1844 /* Set things up such that the next call to darwin_wait will immediately
1845    return a fake stop event for inferior INF.
1846
1847    This assumes that the inferior's thread list has been initialized,
1848    as it will suspend the inferior's first thread.  */
1849
1850 static void
1851 darwin_setup_fake_stop_event (struct inferior *inf)
1852 {
1853   darwin_thread_t *thread;
1854   kern_return_t kret;
1855
1856   gdb_assert (darwin_inf_fake_stop == NULL);
1857   darwin_inf_fake_stop = inf;
1858
1859   /* When detecting a fake pending stop event, darwin_wait returns
1860      an event saying that the first thread is in a DARWIN_STOPPED
1861      state.  To make that accurate, we need to suspend that thread
1862      as well.  Otherwise, we'll try resuming it when resuming the
1863      inferior, and get a warning because the thread's suspend count
1864      is already zero, making the resume request useless.  */
1865   thread = VEC_index (darwin_thread_t, inf->priv->threads, 0);
1866   kret = thread_suspend (thread->gdb_port);
1867   MACH_CHECK_ERROR (kret);
1868 }
1869
1870 /* Attach to process PID, then initialize for debugging it
1871    and wait for the trace-trap that results from attaching.  */
1872 static void
1873 darwin_attach (struct target_ops *ops, const char *args, int from_tty)
1874 {
1875   pid_t pid;
1876   pid_t pid2;
1877   int wstatus;
1878   int res;
1879   struct inferior *inf;
1880   kern_return_t kret;
1881
1882   pid = parse_pid_to_attach (args);
1883
1884   if (pid == getpid ())         /* Trying to masturbate?  */
1885     error (_("I refuse to debug myself!"));
1886
1887   if (from_tty)
1888     {
1889       char *exec_file = get_exec_file (0);
1890
1891       if (exec_file)
1892         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
1893                            target_pid_to_str (pid_to_ptid (pid)));
1894       else
1895         printf_unfiltered (_("Attaching to %s\n"),
1896                            target_pid_to_str (pid_to_ptid (pid)));
1897
1898       gdb_flush (gdb_stdout);
1899     }
1900
1901   if (pid == 0 || kill (pid, 0) < 0)
1902     error (_("Can't attach to process %d: %s (%d)"),
1903            pid, safe_strerror (errno), errno);
1904
1905   inferior_ptid = pid_to_ptid (pid);
1906   inf = current_inferior ();
1907   inferior_appeared (inf, pid);
1908   inf->attach_flag = 1;
1909
1910   darwin_attach_pid (inf);
1911
1912   darwin_suspend_inferior (inf);
1913
1914   darwin_init_thread_list (inf);
1915
1916   darwin_check_osabi (inf->priv, ptid_get_tid (inferior_ptid));
1917
1918   darwin_setup_fake_stop_event (inf);
1919
1920   inf->priv->no_ptrace = 1;
1921 }
1922
1923 /* Take a program previously attached to and detaches it.
1924    The program resumes execution and will no longer stop
1925    on signals, etc.  We'd better not have left any breakpoints
1926    in the program or it'll die when it hits one.  For this
1927    to work, it may be necessary for the process to have been
1928    previously attached.  It *might* work if the program was
1929    started via fork.  */
1930 static void
1931 darwin_detach (struct target_ops *ops, const char *args, int from_tty)
1932 {
1933   pid_t pid = ptid_get_pid (inferior_ptid);
1934   struct inferior *inf = current_inferior ();
1935   kern_return_t kret;
1936   int res;
1937
1938   /* Display message.  */
1939   target_announce_detach (from_tty);
1940
1941   /* If ptrace() is in use, stop the process.  */
1942   if (!inf->priv->no_ptrace)
1943     darwin_stop_inferior (inf);
1944
1945   kret = darwin_restore_exception_ports (inf->priv);
1946   MACH_CHECK_ERROR (kret);
1947
1948   if (!inf->priv->no_ptrace)
1949     {
1950       res = PTRACE (PT_DETACH, inf->pid, 0, 0);
1951       if (res != 0)
1952         printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
1953                            inf->pid, safe_strerror (errno), errno);
1954     }
1955
1956   darwin_reply_to_all_pending_messages (inf);
1957
1958   /* When using ptrace, we have just performed a PT_DETACH, which
1959      resumes the inferior.  On the other hand, when we are not using
1960      ptrace, we need to resume its execution ourselves.  */
1961   if (inf->priv->no_ptrace)
1962     darwin_resume_inferior (inf);
1963
1964   darwin_mourn_inferior (ops);
1965 }
1966
1967 static void
1968 darwin_files_info (struct target_ops *ops)
1969 {
1970 }
1971
1972 static const char *
1973 darwin_pid_to_str (struct target_ops *ops, ptid_t ptid)
1974 {
1975   static char buf[80];
1976   long tid = ptid_get_tid (ptid);
1977
1978   if (tid != 0)
1979     {
1980       snprintf (buf, sizeof (buf), _("Thread 0x%lx of process %u"),
1981                 tid, ptid_get_pid (ptid));
1982       return buf;
1983     }
1984
1985   return normal_pid_to_str (ptid);
1986 }
1987
1988 static int
1989 darwin_thread_alive (struct target_ops *ops, ptid_t ptid)
1990 {
1991   return 1;
1992 }
1993
1994 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
1995    copy it to RDADDR in gdb's address space.
1996    If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
1997    to ADDR in inferior task's address space.
1998    Return 0 on failure; number of bytes read / writen otherwise.  */
1999
2000 static int
2001 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
2002                             gdb_byte *rdaddr, const gdb_byte *wraddr,
2003                             ULONGEST length)
2004 {
2005   kern_return_t kret;
2006   mach_vm_size_t res_length = 0;
2007   pointer_t copied;
2008   mach_msg_type_number_t copy_count;
2009   mach_vm_size_t remaining_length;
2010   mach_vm_address_t region_address;
2011   mach_vm_size_t region_length;
2012
2013   inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
2014                   task, core_addr_to_string (addr), pulongest (length));
2015
2016   /* First read.  */
2017   if (rdaddr != NULL)
2018     {
2019       mach_vm_size_t count;
2020
2021       /* According to target.h(to_xfer_partial), one and only one may be
2022          non-null.  */
2023       gdb_assert (wraddr == NULL);
2024
2025       kret = mach_vm_read_overwrite (task, addr, length,
2026                                      (mach_vm_address_t) rdaddr, &count);
2027       if (kret != KERN_SUCCESS)
2028         {
2029           inferior_debug
2030             (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
2031              core_addr_to_string (addr), mach_error_string (kret));
2032           return 0;
2033         }
2034       return count;
2035     }
2036
2037   /* See above.  */
2038   gdb_assert (wraddr != NULL);
2039
2040   while (length != 0)
2041     {
2042       mach_vm_address_t offset = addr & (mach_page_size - 1);
2043       mach_vm_address_t region_address = (mach_vm_address_t) (addr - offset);
2044       mach_vm_size_t aligned_length =
2045         (mach_vm_size_t) PAGE_ROUND (offset + length);
2046       vm_region_submap_short_info_data_64_t info;
2047       mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
2048       natural_t region_depth = 1000;
2049       mach_vm_address_t region_start = region_address;
2050       mach_vm_size_t region_length;
2051       mach_vm_size_t write_length;
2052
2053       /* Read page protection.  */
2054       kret = mach_vm_region_recurse
2055         (task, &region_start, &region_length, &region_depth,
2056          (vm_region_recurse_info_t) &info, &count);
2057
2058       if (kret != KERN_SUCCESS)
2059         {
2060           inferior_debug (1, _("darwin_read_write_inferior: "
2061                                "mach_vm_region_recurse failed at %s: %s\n"),
2062                           core_addr_to_string (region_address),
2063                           mach_error_string (kret));
2064           return res_length;
2065         }
2066
2067       inferior_debug
2068         (9, _("darwin_read_write_inferior: "
2069               "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
2070          core_addr_to_string (region_address),
2071          core_addr_to_string (region_start),
2072          core_addr_to_string (region_length));
2073
2074       /* Check for holes in memory.  */
2075       if (region_start > region_address)
2076         {
2077           warning (_("No memory at %s (vs %s+0x%x).  Nothing written"),
2078                    core_addr_to_string (region_address),
2079                    core_addr_to_string (region_start),
2080                    (unsigned)region_length);
2081           return res_length;
2082         }
2083
2084       /* Adjust the length.  */
2085       region_length -= (region_address - region_start);
2086       if (region_length > aligned_length)
2087         region_length = aligned_length;
2088
2089       /* Make the pages RW.  */
2090       if (!(info.protection & VM_PROT_WRITE))
2091         {
2092           vm_prot_t prot = VM_PROT_READ | VM_PROT_WRITE;
2093
2094           kret = mach_vm_protect (task, region_address, region_length,
2095                                   FALSE, prot);
2096           if (kret != KERN_SUCCESS)
2097             {
2098               prot |= VM_PROT_COPY;
2099               kret = mach_vm_protect (task, region_address, region_length,
2100                                       FALSE, prot);
2101             }
2102           if (kret != KERN_SUCCESS)
2103             {
2104               warning (_("darwin_read_write_inferior: "
2105                          "mach_vm_protect failed at %s "
2106                          "(len=0x%lx, prot=0x%x): %s"),
2107                        core_addr_to_string (region_address),
2108                        (unsigned long) region_length, (unsigned) prot,
2109                        mach_error_string (kret));
2110               return res_length;
2111             }
2112         }
2113
2114       if (offset + length > region_length)
2115         write_length = region_length - offset;
2116       else
2117         write_length = length;
2118
2119       /* Write.  */
2120       kret = mach_vm_write (task, addr, (vm_offset_t) wraddr, write_length);
2121       if (kret != KERN_SUCCESS)
2122         {
2123           warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
2124                    mach_error_string (kret));
2125           return res_length;
2126         }
2127
2128       /* Restore page rights.  */
2129       if (!(info.protection & VM_PROT_WRITE))
2130         {
2131           kret = mach_vm_protect (task, region_address, region_length,
2132                                   FALSE, info.protection);
2133           if (kret != KERN_SUCCESS)
2134             {
2135               warning (_("darwin_read_write_inferior: "
2136                          "mach_vm_protect restore failed at %s "
2137                          "(len=0x%lx): %s"),
2138                        core_addr_to_string (region_address),
2139                        (unsigned long) region_length,
2140                        mach_error_string (kret));
2141             }
2142         }
2143
2144       addr += write_length;
2145       wraddr += write_length;
2146       res_length += write_length;
2147       length -= write_length;
2148     }
2149
2150   return res_length;
2151 }
2152
2153 /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
2154    to RDADDR (in big endian).
2155    Return 0 on failure; number of bytes read / written otherwise.  */
2156
2157 #ifdef TASK_DYLD_INFO_COUNT
2158 /* This is not available in Darwin 9.  */
2159 static enum target_xfer_status
2160 darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
2161                        ULONGEST length, ULONGEST *xfered_len)
2162 {
2163   struct task_dyld_info task_dyld_info;
2164   mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
2165   int sz = TASK_DYLD_INFO_COUNT * sizeof (natural_t);
2166   kern_return_t kret;
2167
2168   if (addr != 0 || length > sizeof (mach_vm_address_t))
2169     return TARGET_XFER_EOF;
2170
2171   kret = task_info (task, TASK_DYLD_INFO,
2172                     (task_info_t) &task_dyld_info, &count);
2173   MACH_CHECK_ERROR (kret);
2174   if (kret != KERN_SUCCESS)
2175     return TARGET_XFER_E_IO;
2176
2177   store_unsigned_integer (rdaddr, length, BFD_ENDIAN_BIG,
2178                           task_dyld_info.all_image_info_addr);
2179   *xfered_len = (ULONGEST) length;
2180   return TARGET_XFER_OK;
2181 }
2182 #endif
2183
2184 \f
2185
2186 static enum target_xfer_status
2187 darwin_xfer_partial (struct target_ops *ops,
2188                      enum target_object object, const char *annex,
2189                      gdb_byte *readbuf, const gdb_byte *writebuf,
2190                      ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
2191 {
2192   struct inferior *inf = current_inferior ();
2193
2194   inferior_debug
2195     (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
2196      core_addr_to_string (offset), pulongest (len),
2197      host_address_to_string (readbuf), host_address_to_string (writebuf),
2198      inf->pid);
2199
2200   switch (object)
2201     {
2202     case TARGET_OBJECT_MEMORY:
2203       {
2204         int l = darwin_read_write_inferior (inf->priv->task, offset,
2205                                             readbuf, writebuf, len);
2206
2207         if (l == 0)
2208           return TARGET_XFER_EOF;
2209         else
2210           {
2211             gdb_assert (l > 0);
2212             *xfered_len = (ULONGEST) l;
2213             return TARGET_XFER_OK;
2214           }
2215       }
2216 #ifdef TASK_DYLD_INFO_COUNT
2217     case TARGET_OBJECT_DARWIN_DYLD_INFO:
2218       if (writebuf != NULL || readbuf == NULL)
2219         {
2220           /* Support only read.  */
2221           return TARGET_XFER_E_IO;
2222         }
2223       return darwin_read_dyld_info (inf->priv->task, offset, readbuf, len,
2224                                     xfered_len);
2225 #endif
2226     default:
2227       return TARGET_XFER_E_IO;
2228     }
2229
2230 }
2231
2232 static void
2233 set_enable_mach_exceptions (char *args, int from_tty,
2234                             struct cmd_list_element *c)
2235 {
2236   if (!ptid_equal (inferior_ptid, null_ptid))
2237     {
2238       struct inferior *inf = current_inferior ();
2239       exception_mask_t mask;
2240       kern_return_t kret;
2241
2242       if (enable_mach_exceptions)
2243         mask = EXC_MASK_ALL;
2244       else
2245         {
2246           darwin_restore_exception_ports (inf->priv);
2247           mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
2248         }
2249       kret = task_set_exception_ports (inf->priv->task, mask, darwin_ex_port,
2250                                        EXCEPTION_DEFAULT, THREAD_STATE_NONE);
2251       MACH_CHECK_ERROR (kret);
2252     }
2253 }
2254
2255 static char *
2256 darwin_pid_to_exec_file (struct target_ops *self, int pid)
2257 {
2258   static char path[PATH_MAX];
2259   int res;
2260
2261   res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
2262   if (res >= 0)
2263     return path;
2264   else
2265     return NULL;
2266 }
2267
2268 static ptid_t
2269 darwin_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
2270 {
2271   int i;
2272   darwin_thread_t *t;
2273   int k;
2274   struct inferior *inf = current_inferior ();
2275   kern_return_t kret;
2276   mach_port_name_array_t names;
2277   mach_msg_type_number_t names_count;
2278   mach_port_type_array_t types;
2279   mach_msg_type_number_t types_count;
2280   long res = 0;
2281
2282   /* First linear search.  */
2283   for (k = 0;
2284        VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
2285        k++)
2286     if (t->inf_port == lwp)
2287       return ptid_build (ptid_get_pid (inferior_ptid), 0, t->gdb_port);
2288
2289   /* Maybe the port was never extract.  Do it now.  */
2290
2291   /* First get inferior port names.  */
2292   kret = mach_port_names (inf->priv->task, &names, &names_count, &types,
2293                           &types_count);
2294   MACH_CHECK_ERROR (kret);
2295   if (kret != KERN_SUCCESS)
2296     return null_ptid;
2297
2298   /* For each name, copy the right in the gdb space and then compare with
2299      our view of the inferior threads.  We don't forget to deallocate the
2300      right.  */
2301   for (i = 0; i < names_count; i++)
2302     {
2303       mach_port_t local_name;
2304       mach_msg_type_name_t local_type;
2305
2306       /* We just need to know the corresponding name in gdb name space.
2307          So extract and deallocate the right.  */
2308       kret = mach_port_extract_right (inf->priv->task, names[i],
2309                                       MACH_MSG_TYPE_COPY_SEND,
2310                                       &local_name, &local_type);
2311       if (kret != KERN_SUCCESS)
2312         continue;
2313       mach_port_deallocate (gdb_task, local_name);
2314
2315       for (k = 0;
2316            VEC_iterate (darwin_thread_t, inf->priv->threads, k, t);
2317            k++)
2318         if (t->gdb_port == local_name)
2319           {
2320             t->inf_port = names[i];
2321             if (names[i] == lwp)
2322               res = t->gdb_port;
2323           }
2324     }
2325
2326   vm_deallocate (gdb_task, (vm_address_t) names,
2327                  names_count * sizeof (mach_port_t));
2328
2329   if (res)
2330     return ptid_build (ptid_get_pid (inferior_ptid), 0, res);
2331   else
2332     return null_ptid;
2333 }
2334
2335 static int
2336 darwin_supports_multi_process (struct target_ops *self)
2337 {
2338   return 1;
2339 }
2340
2341 void
2342 _initialize_darwin_inferior (void)
2343 {
2344   kern_return_t kret;
2345
2346   gdb_task = mach_task_self ();
2347   darwin_host_self = mach_host_self ();
2348
2349   /* Read page size.  */
2350   kret = host_page_size (darwin_host_self, &mach_page_size);
2351   if (kret != KERN_SUCCESS)
2352     {
2353       mach_page_size = 0x1000;
2354       MACH_CHECK_ERROR (kret);
2355     }
2356
2357   darwin_ops = inf_child_target ();
2358
2359   darwin_ops->to_create_inferior = darwin_create_inferior;
2360   darwin_ops->to_attach = darwin_attach;
2361   darwin_ops->to_attach_no_wait = 0;
2362   darwin_ops->to_detach = darwin_detach;
2363   darwin_ops->to_files_info = darwin_files_info;
2364   darwin_ops->to_wait = darwin_wait_to;
2365   darwin_ops->to_mourn_inferior = darwin_mourn_inferior;
2366   darwin_ops->to_kill = darwin_kill_inferior;
2367   darwin_ops->to_interrupt = darwin_interrupt;
2368   darwin_ops->to_resume = darwin_resume_to;
2369   darwin_ops->to_thread_alive = darwin_thread_alive;
2370   darwin_ops->to_pid_to_str = darwin_pid_to_str;
2371   darwin_ops->to_pid_to_exec_file = darwin_pid_to_exec_file;
2372   darwin_ops->to_load = NULL;
2373   darwin_ops->to_xfer_partial = darwin_xfer_partial;
2374   darwin_ops->to_supports_multi_process = darwin_supports_multi_process;
2375   darwin_ops->to_get_ada_task_ptid = darwin_get_ada_task_ptid;
2376
2377   darwin_complete_target (darwin_ops);
2378
2379   add_target (darwin_ops);
2380
2381   inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"),
2382                   (unsigned long) mach_task_self (), getpid ());
2383
2384   add_setshow_zuinteger_cmd ("darwin", class_obscure,
2385                              &darwin_debug_flag, _("\
2386 Set if printing inferior communication debugging statements."), _("\
2387 Show if printing inferior communication debugging statements."), NULL,
2388                              NULL, NULL,
2389                              &setdebuglist, &showdebuglist);
2390
2391   add_setshow_boolean_cmd ("mach-exceptions", class_support,
2392                            &enable_mach_exceptions, _("\
2393 Set if mach exceptions are caught."), _("\
2394 Show if mach exceptions are caught."), _("\
2395 When this mode is on, all low level exceptions are reported before being\n\
2396 reported by the kernel."),
2397                            &set_enable_mach_exceptions, NULL,
2398                            &setlist, &showlist);
2399 }