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