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