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