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